database.inc 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098
  1. <?php
  2. /**
  3. * @file
  4. * Core systems for the database layer.
  5. *
  6. * Classes required for basic functioning of the database system should be
  7. * placed in this file. All utility functions should also be placed in this
  8. * file only, as they cannot auto-load the way classes can.
  9. */
  10. /**
  11. * @defgroup database Database abstraction layer
  12. * @{
  13. * Allow the use of different database servers using the same code base.
  14. *
  15. * Drupal provides a database abstraction layer to provide developers with
  16. * the ability to support multiple database servers easily. The intent of
  17. * this layer is to preserve the syntax and power of SQL as much as possible,
  18. * but also allow developers a way to leverage more complex functionality in
  19. * a unified way. It also provides a structured interface for dynamically
  20. * constructing queries when appropriate, and enforcing security checks and
  21. * similar good practices.
  22. *
  23. * The system is built atop PHP's PDO (PHP Data Objects) database API and
  24. * inherits much of its syntax and semantics.
  25. *
  26. * Most Drupal database SELECT queries are performed by a call to db_query() or
  27. * db_query_range(). Module authors should also consider using the PagerDefault
  28. * Extender for queries that return results that need to be presented on
  29. * multiple pages (see https://drupal.org/node/508796), and the TableSort
  30. * Extender for generating appropriate queries for sortable tables
  31. * (see https://drupal.org/node/1848372).
  32. *
  33. * For example, one might wish to return a list of the most recent 10 nodes
  34. * authored by a given user. Instead of directly issuing the SQL query
  35. * @code
  36. * SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid
  37. * ORDER BY n.created DESC LIMIT 0, 10;
  38. * @endcode
  39. * one would instead call the Drupal functions:
  40. * @code
  41. * $result = db_query_range('SELECT n.nid, n.title, n.created
  42. * FROM {node} n WHERE n.uid = :uid
  43. * ORDER BY n.created DESC', 0, 10, array(':uid' => $uid));
  44. * foreach ($result as $record) {
  45. * // Perform operations on $record->title, etc. here.
  46. * }
  47. * @endcode
  48. * Curly braces are used around "node" to provide table prefixing via
  49. * DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled
  50. * out into an argument passed to db_query() so that SQL injection attacks
  51. * from user input can be caught and nullified. The LIMIT syntax varies between
  52. * database servers, so that is abstracted into db_query_range() arguments.
  53. * Finally, note the PDO-based ability to iterate over the result set using
  54. * foreach ().
  55. *
  56. * All queries are passed as a prepared statement string. A
  57. * prepared statement is a "template" of a query that omits literal or variable
  58. * values in favor of placeholders. The values to place into those
  59. * placeholders are passed separately, and the database driver handles
  60. * inserting the values into the query in a secure fashion. That means you
  61. * should never quote or string-escape a value to be inserted into the query.
  62. *
  63. * There are two formats for placeholders: named and unnamed. Named placeholders
  64. * are strongly preferred in all cases as they are more flexible and
  65. * self-documenting. Named placeholders should start with a colon ":" and can be
  66. * followed by one or more letters, numbers or underscores.
  67. *
  68. * Named placeholders begin with a colon followed by a unique string. Example:
  69. * @code
  70. * SELECT nid, title FROM {node} WHERE uid=:uid;
  71. * @endcode
  72. *
  73. * ":uid" is a placeholder that will be replaced with a literal value when
  74. * the query is executed. A given placeholder label cannot be repeated in a
  75. * given query, even if the value should be the same. When using named
  76. * placeholders, the array of arguments to the query must be an associative
  77. * array where keys are a placeholder label (e.g., :uid) and the value is the
  78. * corresponding value to use. The array may be in any order.
  79. *
  80. * Unnamed placeholders are simply a question mark. Example:
  81. * @code
  82. * SELECT nid, title FROM {node} WHERE uid=?;
  83. * @endcode
  84. *
  85. * In this case, the array of arguments must be an indexed array of values to
  86. * use in the exact same order as the placeholders in the query.
  87. *
  88. * Note that placeholders should be a "complete" value. For example, when
  89. * running a LIKE query the SQL wildcard character, %, should be part of the
  90. * value, not the query itself. Thus, the following is incorrect:
  91. * @code
  92. * SELECT nid, title FROM {node} WHERE title LIKE :title%;
  93. * @endcode
  94. * It should instead read:
  95. * @code
  96. * SELECT nid, title FROM {node} WHERE title LIKE :title;
  97. * @endcode
  98. * and the value for :title should include a % as appropriate. Again, note the
  99. * lack of quotation marks around :title. Because the value is not inserted
  100. * into the query as one big string but as an explicitly separate value, the
  101. * database server knows where the query ends and a value begins. That is
  102. * considerably more secure against SQL injection than trying to remember
  103. * which values need quotation marks and string escaping and which don't.
  104. *
  105. * INSERT, UPDATE, and DELETE queries need special care in order to behave
  106. * consistently across all different databases. Therefore, they use a special
  107. * object-oriented API for defining a query structurally. For example, rather
  108. * than:
  109. * @code
  110. * INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body');
  111. * @endcode
  112. * one would instead write:
  113. * @code
  114. * $fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
  115. * db_insert('node')->fields($fields)->execute();
  116. * @endcode
  117. * This method allows databases that need special data type handling to do so,
  118. * while also allowing optimizations such as multi-insert queries. UPDATE and
  119. * DELETE queries have a similar pattern.
  120. *
  121. * Drupal also supports transactions, including a transparent fallback for
  122. * databases that do not support transactions. To start a new transaction,
  123. * simply call $txn = db_transaction(); in your own code. The transaction will
  124. * remain open for as long as the variable $txn remains in scope. When $txn is
  125. * destroyed, the transaction will be committed. If your transaction is nested
  126. * inside of another then Drupal will track each transaction and only commit
  127. * the outer-most transaction when the last transaction object goes out out of
  128. * scope, that is, all relevant queries completed successfully.
  129. *
  130. * Example:
  131. * @code
  132. * function my_transaction_function() {
  133. * // The transaction opens here.
  134. * $txn = db_transaction();
  135. *
  136. * try {
  137. * $id = db_insert('example')
  138. * ->fields(array(
  139. * 'field1' => 'mystring',
  140. * 'field2' => 5,
  141. * ))
  142. * ->execute();
  143. *
  144. * my_other_function($id);
  145. *
  146. * return $id;
  147. * }
  148. * catch (Exception $e) {
  149. * // Something went wrong somewhere, so roll back now.
  150. * $txn->rollback();
  151. * // Log the exception to watchdog.
  152. * watchdog_exception('type', $e);
  153. * }
  154. *
  155. * // $txn goes out of scope here. Unless the transaction was rolled back, it
  156. * // gets automatically committed here.
  157. * }
  158. *
  159. * function my_other_function($id) {
  160. * // The transaction is still open here.
  161. *
  162. * if ($id % 2 == 0) {
  163. * db_update('example')
  164. * ->condition('id', $id)
  165. * ->fields(array('field2' => 10))
  166. * ->execute();
  167. * }
  168. * }
  169. * @endcode
  170. *
  171. * @see http://drupal.org/developing/api/database
  172. */
  173. /**
  174. * Base Database API class.
  175. *
  176. * This class provides a Drupal-specific extension of the PDO database
  177. * abstraction class in PHP. Every database driver implementation must provide a
  178. * concrete implementation of it to support special handling required by that
  179. * database.
  180. *
  181. * @see http://php.net/manual/book.pdo.php
  182. */
  183. abstract class DatabaseConnection extends PDO {
  184. /**
  185. * The database target this connection is for.
  186. *
  187. * We need this information for later auditing and logging.
  188. *
  189. * @var string
  190. */
  191. protected $target = NULL;
  192. /**
  193. * The key representing this connection.
  194. *
  195. * The key is a unique string which identifies a database connection. A
  196. * connection can be a single server or a cluster of master and slaves (use
  197. * target to pick between master and slave).
  198. *
  199. * @var string
  200. */
  201. protected $key = NULL;
  202. /**
  203. * The current database logging object for this connection.
  204. *
  205. * @var DatabaseLog
  206. */
  207. protected $logger = NULL;
  208. /**
  209. * Tracks the number of "layers" of transactions currently active.
  210. *
  211. * On many databases transactions cannot nest. Instead, we track
  212. * nested calls to transactions and collapse them into a single
  213. * transaction.
  214. *
  215. * @var array
  216. */
  217. protected $transactionLayers = array();
  218. /**
  219. * Index of what driver-specific class to use for various operations.
  220. *
  221. * @var array
  222. */
  223. protected $driverClasses = array();
  224. /**
  225. * The name of the Statement class for this connection.
  226. *
  227. * @var string
  228. */
  229. protected $statementClass = 'DatabaseStatementBase';
  230. /**
  231. * Whether this database connection supports transactions.
  232. *
  233. * @var bool
  234. */
  235. protected $transactionSupport = TRUE;
  236. /**
  237. * Whether this database connection supports transactional DDL.
  238. *
  239. * Set to FALSE by default because few databases support this feature.
  240. *
  241. * @var bool
  242. */
  243. protected $transactionalDDLSupport = FALSE;
  244. /**
  245. * An index used to generate unique temporary table names.
  246. *
  247. * @var integer
  248. */
  249. protected $temporaryNameIndex = 0;
  250. /**
  251. * The connection information for this connection object.
  252. *
  253. * @var array
  254. */
  255. protected $connectionOptions = array();
  256. /**
  257. * The schema object for this connection.
  258. *
  259. * @var object
  260. */
  261. protected $schema = NULL;
  262. /**
  263. * The prefixes used by this database connection.
  264. *
  265. * @var array
  266. */
  267. protected $prefixes = array();
  268. /**
  269. * List of search values for use in prefixTables().
  270. *
  271. * @var array
  272. */
  273. protected $prefixSearch = array();
  274. /**
  275. * List of replacement values for use in prefixTables().
  276. *
  277. * @var array
  278. */
  279. protected $prefixReplace = array();
  280. /**
  281. * List of escaped database, table, and field names, keyed by unescaped names.
  282. *
  283. * @var array
  284. */
  285. protected $escapedNames = array();
  286. /**
  287. * List of escaped aliases names, keyed by unescaped aliases.
  288. *
  289. * @var array
  290. */
  291. protected $escapedAliases = array();
  292. function __construct($dsn, $username, $password, $driver_options = array()) {
  293. // Initialize and prepare the connection prefix.
  294. $this->setPrefix(isset($this->connectionOptions['prefix']) ? $this->connectionOptions['prefix'] : '');
  295. // Because the other methods don't seem to work right.
  296. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
  297. // Call PDO::__construct and PDO::setAttribute.
  298. parent::__construct($dsn, $username, $password, $driver_options);
  299. // Set a Statement class, unless the driver opted out.
  300. if (!empty($this->statementClass)) {
  301. $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
  302. }
  303. }
  304. /**
  305. * Destroys this Connection object.
  306. *
  307. * PHP does not destruct an object if it is still referenced in other
  308. * variables. In case of PDO database connection objects, PHP only closes the
  309. * connection when the PDO object is destructed, so any references to this
  310. * object may cause the number of maximum allowed connections to be exceeded.
  311. */
  312. public function destroy() {
  313. // Destroy all references to this connection by setting them to NULL.
  314. // The Statement class attribute only accepts a new value that presents a
  315. // proper callable, so we reset it to PDOStatement.
  316. $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement', array()));
  317. $this->schema = NULL;
  318. }
  319. /**
  320. * Returns the default query options for any given query.
  321. *
  322. * A given query can be customized with a number of option flags in an
  323. * associative array:
  324. * - target: The database "target" against which to execute a query. Valid
  325. * values are "default" or "slave". The system will first try to open a
  326. * connection to a database specified with the user-supplied key. If one
  327. * is not available, it will silently fall back to the "default" target.
  328. * If multiple databases connections are specified with the same target,
  329. * one will be selected at random for the duration of the request.
  330. * - fetch: This element controls how rows from a result set will be
  331. * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
  332. * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
  333. * class. If a string is specified, each record will be fetched into a new
  334. * object of that class. The behavior of all other values is defined by PDO.
  335. * See http://php.net/manual/pdostatement.fetch.php
  336. * - return: Depending on the type of query, different return values may be
  337. * meaningful. This directive instructs the system which type of return
  338. * value is desired. The system will generally set the correct value
  339. * automatically, so it is extremely rare that a module developer will ever
  340. * need to specify this value. Setting it incorrectly will likely lead to
  341. * unpredictable results or fatal errors. Legal values include:
  342. * - Database::RETURN_STATEMENT: Return the prepared statement object for
  343. * the query. This is usually only meaningful for SELECT queries, where
  344. * the statement object is how one accesses the result set returned by the
  345. * query.
  346. * - Database::RETURN_AFFECTED: Return the number of rows affected by an
  347. * UPDATE or DELETE query. Be aware that means the number of rows actually
  348. * changed, not the number of rows matched by the WHERE clause.
  349. * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
  350. * created by an INSERT statement on a table that contains a serial
  351. * column.
  352. * - Database::RETURN_NULL: Do not return anything, as there is no
  353. * meaningful value to return. That is the case for INSERT queries on
  354. * tables that do not contain a serial column.
  355. * - throw_exception: By default, the database system will catch any errors
  356. * on a query as an Exception, log it, and then rethrow it so that code
  357. * further up the call chain can take an appropriate action. To suppress
  358. * that behavior and simply return NULL on failure, set this option to
  359. * FALSE.
  360. *
  361. * @return
  362. * An array of default query options.
  363. */
  364. protected function defaultOptions() {
  365. return array(
  366. 'target' => 'default',
  367. 'fetch' => PDO::FETCH_OBJ,
  368. 'return' => Database::RETURN_STATEMENT,
  369. 'throw_exception' => TRUE,
  370. );
  371. }
  372. /**
  373. * Returns the connection information for this connection object.
  374. *
  375. * Note that Database::getConnectionInfo() is for requesting information
  376. * about an arbitrary database connection that is defined. This method
  377. * is for requesting the connection information of this specific
  378. * open connection object.
  379. *
  380. * @return
  381. * An array of the connection information. The exact list of
  382. * properties is driver-dependent.
  383. */
  384. public function getConnectionOptions() {
  385. return $this->connectionOptions;
  386. }
  387. /**
  388. * Set the list of prefixes used by this database connection.
  389. *
  390. * @param $prefix
  391. * The prefixes, in any of the multiple forms documented in
  392. * default.settings.php.
  393. */
  394. protected function setPrefix($prefix) {
  395. if (is_array($prefix)) {
  396. $this->prefixes = $prefix + array('default' => '');
  397. }
  398. else {
  399. $this->prefixes = array('default' => $prefix);
  400. }
  401. // Set up variables for use in prefixTables(). Replace table-specific
  402. // prefixes first.
  403. $this->prefixSearch = array();
  404. $this->prefixReplace = array();
  405. foreach ($this->prefixes as $key => $val) {
  406. if ($key != 'default') {
  407. $this->prefixSearch[] = '{' . $key . '}';
  408. $this->prefixReplace[] = $val . $key;
  409. }
  410. }
  411. // Then replace remaining tables with the default prefix.
  412. $this->prefixSearch[] = '{';
  413. $this->prefixReplace[] = $this->prefixes['default'];
  414. $this->prefixSearch[] = '}';
  415. $this->prefixReplace[] = '';
  416. }
  417. /**
  418. * Appends a database prefix to all tables in a query.
  419. *
  420. * Queries sent to Drupal should wrap all table names in curly brackets. This
  421. * function searches for this syntax and adds Drupal's table prefix to all
  422. * tables, allowing Drupal to coexist with other systems in the same database
  423. * and/or schema if necessary.
  424. *
  425. * @param $sql
  426. * A string containing a partial or entire SQL query.
  427. *
  428. * @return
  429. * The properly-prefixed string.
  430. */
  431. public function prefixTables($sql) {
  432. return str_replace($this->prefixSearch, $this->prefixReplace, $sql);
  433. }
  434. /**
  435. * Find the prefix for a table.
  436. *
  437. * This function is for when you want to know the prefix of a table. This
  438. * is not used in prefixTables due to performance reasons.
  439. */
  440. public function tablePrefix($table = 'default') {
  441. if (isset($this->prefixes[$table])) {
  442. return $this->prefixes[$table];
  443. }
  444. else {
  445. return $this->prefixes['default'];
  446. }
  447. }
  448. /**
  449. * Prepares a query string and returns the prepared statement.
  450. *
  451. * This method caches prepared statements, reusing them when
  452. * possible. It also prefixes tables names enclosed in curly-braces.
  453. *
  454. * @param $query
  455. * The query string as SQL, with curly-braces surrounding the
  456. * table names.
  457. *
  458. * @return DatabaseStatementInterface
  459. * A PDO prepared statement ready for its execute() method.
  460. */
  461. public function prepareQuery($query) {
  462. $query = $this->prefixTables($query);
  463. // Call PDO::prepare.
  464. return parent::prepare($query);
  465. }
  466. /**
  467. * Tells this connection object what its target value is.
  468. *
  469. * This is needed for logging and auditing. It's sloppy to do in the
  470. * constructor because the constructor for child classes has a different
  471. * signature. We therefore also ensure that this function is only ever
  472. * called once.
  473. *
  474. * @param $target
  475. * The target this connection is for. Set to NULL (default) to disable
  476. * logging entirely.
  477. */
  478. public function setTarget($target = NULL) {
  479. if (!isset($this->target)) {
  480. $this->target = $target;
  481. }
  482. }
  483. /**
  484. * Returns the target this connection is associated with.
  485. *
  486. * @return
  487. * The target string of this connection.
  488. */
  489. public function getTarget() {
  490. return $this->target;
  491. }
  492. /**
  493. * Tells this connection object what its key is.
  494. *
  495. * @param $target
  496. * The key this connection is for.
  497. */
  498. public function setKey($key) {
  499. if (!isset($this->key)) {
  500. $this->key = $key;
  501. }
  502. }
  503. /**
  504. * Returns the key this connection is associated with.
  505. *
  506. * @return
  507. * The key of this connection.
  508. */
  509. public function getKey() {
  510. return $this->key;
  511. }
  512. /**
  513. * Associates a logging object with this connection.
  514. *
  515. * @param $logger
  516. * The logging object we want to use.
  517. */
  518. public function setLogger(DatabaseLog $logger) {
  519. $this->logger = $logger;
  520. }
  521. /**
  522. * Gets the current logging object for this connection.
  523. *
  524. * @return DatabaseLog
  525. * The current logging object for this connection. If there isn't one,
  526. * NULL is returned.
  527. */
  528. public function getLogger() {
  529. return $this->logger;
  530. }
  531. /**
  532. * Creates the appropriate sequence name for a given table and serial field.
  533. *
  534. * This information is exposed to all database drivers, although it is only
  535. * useful on some of them. This method is table prefix-aware.
  536. *
  537. * @param $table
  538. * The table name to use for the sequence.
  539. * @param $field
  540. * The field name to use for the sequence.
  541. *
  542. * @return
  543. * A table prefix-parsed string for the sequence name.
  544. */
  545. public function makeSequenceName($table, $field) {
  546. return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
  547. }
  548. /**
  549. * Flatten an array of query comments into a single comment string.
  550. *
  551. * The comment string will be sanitized to avoid SQL injection attacks.
  552. *
  553. * @param $comments
  554. * An array of query comment strings.
  555. *
  556. * @return
  557. * A sanitized comment string.
  558. */
  559. public function makeComment($comments) {
  560. if (empty($comments))
  561. return '';
  562. // Flatten the array of comments.
  563. $comment = implode('; ', $comments);
  564. // Sanitize the comment string so as to avoid SQL injection attacks.
  565. return '/* ' . $this->filterComment($comment) . ' */ ';
  566. }
  567. /**
  568. * Sanitize a query comment string.
  569. *
  570. * Ensure a query comment does not include strings such as "* /" that might
  571. * terminate the comment early. This avoids SQL injection attacks via the
  572. * query comment. The comment strings in this example are separated by a
  573. * space to avoid PHP parse errors.
  574. *
  575. * For example, the comment:
  576. * @code
  577. * db_update('example')
  578. * ->condition('id', $id)
  579. * ->fields(array('field2' => 10))
  580. * ->comment('Exploit * / DROP TABLE node; --')
  581. * ->execute()
  582. * @endcode
  583. *
  584. * Would result in the following SQL statement being generated:
  585. * @code
  586. * "/ * Exploit * / DROP TABLE node; -- * / UPDATE example SET field2=..."
  587. * @endcode
  588. *
  589. * Unless the comment is sanitised first, the SQL server would drop the
  590. * node table and ignore the rest of the SQL statement.
  591. *
  592. * @param $comment
  593. * A query comment string.
  594. *
  595. * @return
  596. * A sanitized version of the query comment string.
  597. */
  598. protected function filterComment($comment = '') {
  599. return strtr($comment, array('*' => ' * '));
  600. }
  601. /**
  602. * Executes a query string against the database.
  603. *
  604. * This method provides a central handler for the actual execution of every
  605. * query. All queries executed by Drupal are executed as PDO prepared
  606. * statements.
  607. *
  608. * @param $query
  609. * The query to execute. In most cases this will be a string containing
  610. * an SQL query with placeholders. An already-prepared instance of
  611. * DatabaseStatementInterface may also be passed in order to allow calling
  612. * code to manually bind variables to a query. If a
  613. * DatabaseStatementInterface is passed, the $args array will be ignored.
  614. * It is extremely rare that module code will need to pass a statement
  615. * object to this method. It is used primarily for database drivers for
  616. * databases that require special LOB field handling.
  617. * @param $args
  618. * An array of arguments for the prepared statement. If the prepared
  619. * statement uses ? placeholders, this array must be an indexed array.
  620. * If it contains named placeholders, it must be an associative array.
  621. * @param $options
  622. * An associative array of options to control how the query is run. See
  623. * the documentation for DatabaseConnection::defaultOptions() for details.
  624. *
  625. * @return DatabaseStatementInterface
  626. * This method will return one of: the executed statement, the number of
  627. * rows affected by the query (not the number matched), or the generated
  628. * insert ID of the last query, depending on the value of
  629. * $options['return']. Typically that value will be set by default or a
  630. * query builder and should not be set by a user. If there is an error,
  631. * this method will return NULL and may throw an exception if
  632. * $options['throw_exception'] is TRUE.
  633. *
  634. * @throws PDOException
  635. */
  636. public function query($query, array $args = array(), $options = array()) {
  637. // Use default values if not already set.
  638. $options += $this->defaultOptions();
  639. try {
  640. // We allow either a pre-bound statement object or a literal string.
  641. // In either case, we want to end up with an executed statement object,
  642. // which we pass to PDOStatement::execute.
  643. if ($query instanceof DatabaseStatementInterface) {
  644. $stmt = $query;
  645. $stmt->execute(NULL, $options);
  646. }
  647. else {
  648. $this->expandArguments($query, $args);
  649. $stmt = $this->prepareQuery($query);
  650. $stmt->execute($args, $options);
  651. }
  652. // Depending on the type of query we may need to return a different value.
  653. // See DatabaseConnection::defaultOptions() for a description of each
  654. // value.
  655. switch ($options['return']) {
  656. case Database::RETURN_STATEMENT:
  657. return $stmt;
  658. case Database::RETURN_AFFECTED:
  659. return $stmt->rowCount();
  660. case Database::RETURN_INSERT_ID:
  661. return $this->lastInsertId();
  662. case Database::RETURN_NULL:
  663. return;
  664. default:
  665. throw new PDOException('Invalid return directive: ' . $options['return']);
  666. }
  667. }
  668. catch (PDOException $e) {
  669. if ($options['throw_exception']) {
  670. // Add additional debug information.
  671. if ($query instanceof DatabaseStatementInterface) {
  672. $e->query_string = $stmt->getQueryString();
  673. }
  674. else {
  675. $e->query_string = $query;
  676. }
  677. $e->args = $args;
  678. throw $e;
  679. }
  680. return NULL;
  681. }
  682. }
  683. /**
  684. * Expands out shorthand placeholders.
  685. *
  686. * Drupal supports an alternate syntax for doing arrays of values. We
  687. * therefore need to expand them out into a full, executable query string.
  688. *
  689. * @param $query
  690. * The query string to modify.
  691. * @param $args
  692. * The arguments for the query.
  693. *
  694. * @return
  695. * TRUE if the query was modified, FALSE otherwise.
  696. */
  697. protected function expandArguments(&$query, &$args) {
  698. $modified = FALSE;
  699. // If the placeholder value to insert is an array, assume that we need
  700. // to expand it out into a comma-delimited set of placeholders.
  701. foreach (array_filter($args, 'is_array') as $key => $data) {
  702. $new_keys = array();
  703. foreach (array_values($data) as $i => $value) {
  704. // This assumes that there are no other placeholders that use the same
  705. // name. For example, if the array placeholder is defined as :example
  706. // and there is already an :example_2 placeholder, this will generate
  707. // a duplicate key. We do not account for that as the calling code
  708. // is already broken if that happens.
  709. $new_keys[$key . '_' . $i] = $value;
  710. }
  711. // Update the query with the new placeholders.
  712. // preg_replace is necessary to ensure the replacement does not affect
  713. // placeholders that start with the same exact text. For example, if the
  714. // query contains the placeholders :foo and :foobar, and :foo has an
  715. // array of values, using str_replace would affect both placeholders,
  716. // but using the following preg_replace would only affect :foo because
  717. // it is followed by a non-word character.
  718. $query = preg_replace('#' . $key . '\b#', implode(', ', array_keys($new_keys)), $query);
  719. // Update the args array with the new placeholders.
  720. unset($args[$key]);
  721. $args += $new_keys;
  722. $modified = TRUE;
  723. }
  724. return $modified;
  725. }
  726. /**
  727. * Gets the driver-specific override class if any for the specified class.
  728. *
  729. * @param string $class
  730. * The class for which we want the potentially driver-specific class.
  731. * @param array $files
  732. * The name of the files in which the driver-specific class can be.
  733. * @param $use_autoload
  734. * If TRUE, attempt to load classes using PHP's autoload capability
  735. * as well as the manual approach here.
  736. * @return string
  737. * The name of the class that should be used for this driver.
  738. */
  739. public function getDriverClass($class, array $files = array(), $use_autoload = FALSE) {
  740. if (empty($this->driverClasses[$class])) {
  741. $driver = $this->driver();
  742. $this->driverClasses[$class] = $class . '_' . $driver;
  743. Database::loadDriverFile($driver, $files);
  744. if (!class_exists($this->driverClasses[$class], $use_autoload)) {
  745. $this->driverClasses[$class] = $class;
  746. }
  747. }
  748. return $this->driverClasses[$class];
  749. }
  750. /**
  751. * Prepares and returns a SELECT query object.
  752. *
  753. * @param $table
  754. * The base table for this query, that is, the first table in the FROM
  755. * clause. This table will also be used as the "base" table for query_alter
  756. * hook implementations.
  757. * @param $alias
  758. * The alias of the base table of this query.
  759. * @param $options
  760. * An array of options on the query.
  761. *
  762. * @return SelectQueryInterface
  763. * An appropriate SelectQuery object for this database connection. Note that
  764. * it may be a driver-specific subclass of SelectQuery, depending on the
  765. * driver.
  766. *
  767. * @see SelectQuery
  768. */
  769. public function select($table, $alias = NULL, array $options = array()) {
  770. $class = $this->getDriverClass('SelectQuery', array('query.inc', 'select.inc'));
  771. return new $class($table, $alias, $this, $options);
  772. }
  773. /**
  774. * Prepares and returns an INSERT query object.
  775. *
  776. * @param $options
  777. * An array of options on the query.
  778. *
  779. * @return InsertQuery
  780. * A new InsertQuery object.
  781. *
  782. * @see InsertQuery
  783. */
  784. public function insert($table, array $options = array()) {
  785. $class = $this->getDriverClass('InsertQuery', array('query.inc'));
  786. return new $class($this, $table, $options);
  787. }
  788. /**
  789. * Prepares and returns a MERGE query object.
  790. *
  791. * @param $options
  792. * An array of options on the query.
  793. *
  794. * @return MergeQuery
  795. * A new MergeQuery object.
  796. *
  797. * @see MergeQuery
  798. */
  799. public function merge($table, array $options = array()) {
  800. $class = $this->getDriverClass('MergeQuery', array('query.inc'));
  801. return new $class($this, $table, $options);
  802. }
  803. /**
  804. * Prepares and returns an UPDATE query object.
  805. *
  806. * @param $options
  807. * An array of options on the query.
  808. *
  809. * @return UpdateQuery
  810. * A new UpdateQuery object.
  811. *
  812. * @see UpdateQuery
  813. */
  814. public function update($table, array $options = array()) {
  815. $class = $this->getDriverClass('UpdateQuery', array('query.inc'));
  816. return new $class($this, $table, $options);
  817. }
  818. /**
  819. * Prepares and returns a DELETE query object.
  820. *
  821. * @param $options
  822. * An array of options on the query.
  823. *
  824. * @return DeleteQuery
  825. * A new DeleteQuery object.
  826. *
  827. * @see DeleteQuery
  828. */
  829. public function delete($table, array $options = array()) {
  830. $class = $this->getDriverClass('DeleteQuery', array('query.inc'));
  831. return new $class($this, $table, $options);
  832. }
  833. /**
  834. * Prepares and returns a TRUNCATE query object.
  835. *
  836. * @param $options
  837. * An array of options on the query.
  838. *
  839. * @return TruncateQuery
  840. * A new TruncateQuery object.
  841. *
  842. * @see TruncateQuery
  843. */
  844. public function truncate($table, array $options = array()) {
  845. $class = $this->getDriverClass('TruncateQuery', array('query.inc'));
  846. return new $class($this, $table, $options);
  847. }
  848. /**
  849. * Returns a DatabaseSchema object for manipulating the schema.
  850. *
  851. * This method will lazy-load the appropriate schema library file.
  852. *
  853. * @return DatabaseSchema
  854. * The DatabaseSchema object for this connection.
  855. */
  856. public function schema() {
  857. if (empty($this->schema)) {
  858. $class = $this->getDriverClass('DatabaseSchema', array('schema.inc'));
  859. if (class_exists($class)) {
  860. $this->schema = new $class($this);
  861. }
  862. }
  863. return $this->schema;
  864. }
  865. /**
  866. * Escapes a table name string.
  867. *
  868. * Force all table names to be strictly alphanumeric-plus-underscore.
  869. * For some database drivers, it may also wrap the table name in
  870. * database-specific escape characters.
  871. *
  872. * @return string
  873. * The sanitized table name string.
  874. */
  875. public function escapeTable($table) {
  876. if (!isset($this->escapedNames[$table])) {
  877. $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
  878. }
  879. return $this->escapedNames[$table];
  880. }
  881. /**
  882. * Escapes a field name string.
  883. *
  884. * Force all field names to be strictly alphanumeric-plus-underscore.
  885. * For some database drivers, it may also wrap the field name in
  886. * database-specific escape characters.
  887. *
  888. * @return string
  889. * The sanitized field name string.
  890. */
  891. public function escapeField($field) {
  892. if (!isset($this->escapedNames[$field])) {
  893. $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
  894. }
  895. return $this->escapedNames[$field];
  896. }
  897. /**
  898. * Escapes an alias name string.
  899. *
  900. * Force all alias names to be strictly alphanumeric-plus-underscore. In
  901. * contrast to DatabaseConnection::escapeField() /
  902. * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
  903. * because that is not allowed in aliases.
  904. *
  905. * @return string
  906. * The sanitized field name string.
  907. */
  908. public function escapeAlias($field) {
  909. if (!isset($this->escapedAliases[$field])) {
  910. $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
  911. }
  912. return $this->escapedAliases[$field];
  913. }
  914. /**
  915. * Escapes characters that work as wildcard characters in a LIKE pattern.
  916. *
  917. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  918. * a backslash. Use this to do a search for a verbatim string without any
  919. * wildcard behavior.
  920. *
  921. * For example, the following does a case-insensitive query for all rows whose
  922. * name starts with $prefix:
  923. * @code
  924. * $result = db_query(
  925. * 'SELECT * FROM person WHERE name LIKE :pattern',
  926. * array(':pattern' => db_like($prefix) . '%')
  927. * );
  928. * @endcode
  929. *
  930. * Backslash is defined as escape character for LIKE patterns in
  931. * DatabaseCondition::mapConditionOperator().
  932. *
  933. * @param $string
  934. * The string to escape.
  935. *
  936. * @return
  937. * The escaped string.
  938. */
  939. public function escapeLike($string) {
  940. return addcslashes($string, '\%_');
  941. }
  942. /**
  943. * Determines if there is an active transaction open.
  944. *
  945. * @return
  946. * TRUE if we're currently in a transaction, FALSE otherwise.
  947. */
  948. public function inTransaction() {
  949. return ($this->transactionDepth() > 0);
  950. }
  951. /**
  952. * Determines current transaction depth.
  953. */
  954. public function transactionDepth() {
  955. return count($this->transactionLayers);
  956. }
  957. /**
  958. * Returns a new DatabaseTransaction object on this connection.
  959. *
  960. * @param $name
  961. * Optional name of the savepoint.
  962. *
  963. * @return DatabaseTransaction
  964. * A DatabaseTransaction object.
  965. *
  966. * @see DatabaseTransaction
  967. */
  968. public function startTransaction($name = '') {
  969. $class = $this->getDriverClass('DatabaseTransaction');
  970. return new $class($this, $name);
  971. }
  972. /**
  973. * Rolls back the transaction entirely or to a named savepoint.
  974. *
  975. * This method throws an exception if no transaction is active.
  976. *
  977. * @param $savepoint_name
  978. * The name of the savepoint. The default, 'drupal_transaction', will roll
  979. * the entire transaction back.
  980. *
  981. * @throws DatabaseTransactionNoActiveException
  982. *
  983. * @see DatabaseTransaction::rollback()
  984. */
  985. public function rollback($savepoint_name = 'drupal_transaction') {
  986. if (!$this->supportsTransactions()) {
  987. return;
  988. }
  989. if (!$this->inTransaction()) {
  990. throw new DatabaseTransactionNoActiveException();
  991. }
  992. // A previous rollback to an earlier savepoint may mean that the savepoint
  993. // in question has already been accidentally committed.
  994. if (!isset($this->transactionLayers[$savepoint_name])) {
  995. throw new DatabaseTransactionNoActiveException();
  996. }
  997. // We need to find the point we're rolling back to, all other savepoints
  998. // before are no longer needed. If we rolled back other active savepoints,
  999. // we need to throw an exception.
  1000. $rolled_back_other_active_savepoints = FALSE;
  1001. while ($savepoint = array_pop($this->transactionLayers)) {
  1002. if ($savepoint == $savepoint_name) {
  1003. // If it is the last the transaction in the stack, then it is not a
  1004. // savepoint, it is the transaction itself so we will need to roll back
  1005. // the transaction rather than a savepoint.
  1006. if (empty($this->transactionLayers)) {
  1007. break;
  1008. }
  1009. $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
  1010. $this->popCommittableTransactions();
  1011. if ($rolled_back_other_active_savepoints) {
  1012. throw new DatabaseTransactionOutOfOrderException();
  1013. }
  1014. return;
  1015. }
  1016. else {
  1017. $rolled_back_other_active_savepoints = TRUE;
  1018. }
  1019. }
  1020. parent::rollBack();
  1021. if ($rolled_back_other_active_savepoints) {
  1022. throw new DatabaseTransactionOutOfOrderException();
  1023. }
  1024. }
  1025. /**
  1026. * Increases the depth of transaction nesting.
  1027. *
  1028. * If no transaction is already active, we begin a new transaction.
  1029. *
  1030. * @throws DatabaseTransactionNameNonUniqueException
  1031. *
  1032. * @see DatabaseTransaction
  1033. */
  1034. public function pushTransaction($name) {
  1035. if (!$this->supportsTransactions()) {
  1036. return;
  1037. }
  1038. if (isset($this->transactionLayers[$name])) {
  1039. throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
  1040. }
  1041. // If we're already in a transaction then we want to create a savepoint
  1042. // rather than try to create another transaction.
  1043. if ($this->inTransaction()) {
  1044. $this->query('SAVEPOINT ' . $name);
  1045. }
  1046. else {
  1047. parent::beginTransaction();
  1048. }
  1049. $this->transactionLayers[$name] = $name;
  1050. }
  1051. /**
  1052. * Decreases the depth of transaction nesting.
  1053. *
  1054. * If we pop off the last transaction layer, then we either commit or roll
  1055. * back the transaction as necessary. If no transaction is active, we return
  1056. * because the transaction may have manually been rolled back.
  1057. *
  1058. * @param $name
  1059. * The name of the savepoint
  1060. *
  1061. * @throws DatabaseTransactionNoActiveException
  1062. * @throws DatabaseTransactionCommitFailedException
  1063. *
  1064. * @see DatabaseTransaction
  1065. */
  1066. public function popTransaction($name) {
  1067. if (!$this->supportsTransactions()) {
  1068. return;
  1069. }
  1070. // The transaction has already been committed earlier. There is nothing we
  1071. // need to do. If this transaction was part of an earlier out-of-order
  1072. // rollback, an exception would already have been thrown by
  1073. // Database::rollback().
  1074. if (!isset($this->transactionLayers[$name])) {
  1075. return;
  1076. }
  1077. // Mark this layer as committable.
  1078. $this->transactionLayers[$name] = FALSE;
  1079. $this->popCommittableTransactions();
  1080. }
  1081. /**
  1082. * Internal function: commit all the transaction layers that can commit.
  1083. */
  1084. protected function popCommittableTransactions() {
  1085. // Commit all the committable layers.
  1086. foreach (array_reverse($this->transactionLayers) as $name => $active) {
  1087. // Stop once we found an active transaction.
  1088. if ($active) {
  1089. break;
  1090. }
  1091. // If there are no more layers left then we should commit.
  1092. unset($this->transactionLayers[$name]);
  1093. if (empty($this->transactionLayers)) {
  1094. if (!parent::commit()) {
  1095. throw new DatabaseTransactionCommitFailedException();
  1096. }
  1097. }
  1098. else {
  1099. $this->query('RELEASE SAVEPOINT ' . $name);
  1100. }
  1101. }
  1102. }
  1103. /**
  1104. * Runs a limited-range query on this database object.
  1105. *
  1106. * Use this as a substitute for ->query() when a subset of the query is to be
  1107. * returned. User-supplied arguments to the query should be passed in as
  1108. * separate parameters so that they can be properly escaped to avoid SQL
  1109. * injection attacks.
  1110. *
  1111. * @param $query
  1112. * A string containing an SQL query.
  1113. * @param $args
  1114. * An array of values to substitute into the query at placeholder markers.
  1115. * @param $from
  1116. * The first result row to return.
  1117. * @param $count
  1118. * The maximum number of result rows to return.
  1119. * @param $options
  1120. * An array of options on the query.
  1121. *
  1122. * @return DatabaseStatementInterface
  1123. * A database query result resource, or NULL if the query was not executed
  1124. * correctly.
  1125. */
  1126. abstract public function queryRange($query, $from, $count, array $args = array(), array $options = array());
  1127. /**
  1128. * Generates a temporary table name.
  1129. *
  1130. * @return
  1131. * A table name.
  1132. */
  1133. protected function generateTemporaryTableName() {
  1134. return "db_temporary_" . $this->temporaryNameIndex++;
  1135. }
  1136. /**
  1137. * Runs a SELECT query and stores its results in a temporary table.
  1138. *
  1139. * Use this as a substitute for ->query() when the results need to stored
  1140. * in a temporary table. Temporary tables exist for the duration of the page
  1141. * request. User-supplied arguments to the query should be passed in as
  1142. * separate parameters so that they can be properly escaped to avoid SQL
  1143. * injection attacks.
  1144. *
  1145. * Note that if you need to know how many results were returned, you should do
  1146. * a SELECT COUNT(*) on the temporary table afterwards.
  1147. *
  1148. * @param $query
  1149. * A string containing a normal SELECT SQL query.
  1150. * @param $args
  1151. * An array of values to substitute into the query at placeholder markers.
  1152. * @param $options
  1153. * An associative array of options to control how the query is run. See
  1154. * the documentation for DatabaseConnection::defaultOptions() for details.
  1155. *
  1156. * @return
  1157. * The name of the temporary table.
  1158. */
  1159. abstract function queryTemporary($query, array $args = array(), array $options = array());
  1160. /**
  1161. * Returns the type of database driver.
  1162. *
  1163. * This is not necessarily the same as the type of the database itself. For
  1164. * instance, there could be two MySQL drivers, mysql and mysql_mock. This
  1165. * function would return different values for each, but both would return
  1166. * "mysql" for databaseType().
  1167. */
  1168. abstract public function driver();
  1169. /**
  1170. * Returns the version of the database server.
  1171. */
  1172. public function version() {
  1173. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  1174. }
  1175. /**
  1176. * Determines if this driver supports transactions.
  1177. *
  1178. * @return
  1179. * TRUE if this connection supports transactions, FALSE otherwise.
  1180. */
  1181. public function supportsTransactions() {
  1182. return $this->transactionSupport;
  1183. }
  1184. /**
  1185. * Determines if this driver supports transactional DDL.
  1186. *
  1187. * DDL queries are those that change the schema, such as ALTER queries.
  1188. *
  1189. * @return
  1190. * TRUE if this connection supports transactions for DDL queries, FALSE
  1191. * otherwise.
  1192. */
  1193. public function supportsTransactionalDDL() {
  1194. return $this->transactionalDDLSupport;
  1195. }
  1196. /**
  1197. * Returns the name of the PDO driver for this connection.
  1198. */
  1199. abstract public function databaseType();
  1200. /**
  1201. * Gets any special processing requirements for the condition operator.
  1202. *
  1203. * Some condition types require special processing, such as IN, because
  1204. * the value data they pass in is not a simple value. This is a simple
  1205. * overridable lookup function. Database connections should define only
  1206. * those operators they wish to be handled differently than the default.
  1207. *
  1208. * @param $operator
  1209. * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
  1210. *
  1211. * @return
  1212. * The extra handling directives for the specified operator, or NULL.
  1213. *
  1214. * @see DatabaseCondition::compile()
  1215. */
  1216. abstract public function mapConditionOperator($operator);
  1217. /**
  1218. * Throws an exception to deny direct access to transaction commits.
  1219. *
  1220. * We do not want to allow users to commit transactions at any time, only
  1221. * by destroying the transaction object or allowing it to go out of scope.
  1222. * A direct commit bypasses all of the safety checks we've built on top of
  1223. * PDO's transaction routines.
  1224. *
  1225. * @throws DatabaseTransactionExplicitCommitNotAllowedException
  1226. *
  1227. * @see DatabaseTransaction
  1228. */
  1229. public function commit() {
  1230. throw new DatabaseTransactionExplicitCommitNotAllowedException();
  1231. }
  1232. /**
  1233. * Retrieves an unique id from a given sequence.
  1234. *
  1235. * Use this function if for some reason you can't use a serial field. For
  1236. * example, MySQL has no ways of reading of the current value of a sequence
  1237. * and PostgreSQL can not advance the sequence to be larger than a given
  1238. * value. Or sometimes you just need a unique integer.
  1239. *
  1240. * @param $existing_id
  1241. * After a database import, it might be that the sequences table is behind,
  1242. * so by passing in the maximum existing id, it can be assured that we
  1243. * never issue the same id.
  1244. *
  1245. * @return
  1246. * An integer number larger than any number returned by earlier calls and
  1247. * also larger than the $existing_id if one was passed in.
  1248. */
  1249. abstract public function nextId($existing_id = 0);
  1250. /**
  1251. * Checks whether utf8mb4 support is configurable in settings.php.
  1252. *
  1253. * @return bool
  1254. */
  1255. public function utf8mb4IsConfigurable() {
  1256. // Since 4 byte UTF-8 is not supported by default, there is nothing to
  1257. // configure.
  1258. return FALSE;
  1259. }
  1260. /**
  1261. * Checks whether utf8mb4 support is currently active.
  1262. *
  1263. * @return bool
  1264. */
  1265. public function utf8mb4IsActive() {
  1266. // Since 4 byte UTF-8 is not supported by default, there is nothing to
  1267. // activate.
  1268. return FALSE;
  1269. }
  1270. /**
  1271. * Checks whether utf8mb4 support is available on the current database system.
  1272. *
  1273. * @return bool
  1274. */
  1275. public function utf8mb4IsSupported() {
  1276. // By default we assume that the database backend may not support 4 byte
  1277. // UTF-8.
  1278. return FALSE;
  1279. }
  1280. }
  1281. /**
  1282. * Primary front-controller for the database system.
  1283. *
  1284. * This class is uninstantiatable and un-extendable. It acts to encapsulate
  1285. * all control and shepherding of database connections into a single location
  1286. * without the use of globals.
  1287. */
  1288. abstract class Database {
  1289. /**
  1290. * Flag to indicate a query call should simply return NULL.
  1291. *
  1292. * This is used for queries that have no reasonable return value anyway, such
  1293. * as INSERT statements to a table without a serial primary key.
  1294. */
  1295. const RETURN_NULL = 0;
  1296. /**
  1297. * Flag to indicate a query call should return the prepared statement.
  1298. */
  1299. const RETURN_STATEMENT = 1;
  1300. /**
  1301. * Flag to indicate a query call should return the number of affected rows.
  1302. */
  1303. const RETURN_AFFECTED = 2;
  1304. /**
  1305. * Flag to indicate a query call should return the "last insert id".
  1306. */
  1307. const RETURN_INSERT_ID = 3;
  1308. /**
  1309. * An nested array of all active connections. It is keyed by database name
  1310. * and target.
  1311. *
  1312. * @var array
  1313. */
  1314. static protected $connections = array();
  1315. /**
  1316. * A processed copy of the database connection information from settings.php.
  1317. *
  1318. * @var array
  1319. */
  1320. static protected $databaseInfo = NULL;
  1321. /**
  1322. * A list of key/target credentials to simply ignore.
  1323. *
  1324. * @var array
  1325. */
  1326. static protected $ignoreTargets = array();
  1327. /**
  1328. * The key of the currently active database connection.
  1329. *
  1330. * @var string
  1331. */
  1332. static protected $activeKey = 'default';
  1333. /**
  1334. * An array of active query log objects.
  1335. *
  1336. * Every connection has one and only one logger object for all targets and
  1337. * logging keys.
  1338. *
  1339. * array(
  1340. * '$db_key' => DatabaseLog object.
  1341. * );
  1342. *
  1343. * @var array
  1344. */
  1345. static protected $logs = array();
  1346. /**
  1347. * Starts logging a given logging key on the specified connection.
  1348. *
  1349. * @param $logging_key
  1350. * The logging key to log.
  1351. * @param $key
  1352. * The database connection key for which we want to log.
  1353. *
  1354. * @return DatabaseLog
  1355. * The query log object. Note that the log object does support richer
  1356. * methods than the few exposed through the Database class, so in some
  1357. * cases it may be desirable to access it directly.
  1358. *
  1359. * @see DatabaseLog
  1360. */
  1361. final public static function startLog($logging_key, $key = 'default') {
  1362. if (empty(self::$logs[$key])) {
  1363. self::$logs[$key] = new DatabaseLog($key);
  1364. // Every target already active for this connection key needs to have the
  1365. // logging object associated with it.
  1366. if (!empty(self::$connections[$key])) {
  1367. foreach (self::$connections[$key] as $connection) {
  1368. $connection->setLogger(self::$logs[$key]);
  1369. }
  1370. }
  1371. }
  1372. self::$logs[$key]->start($logging_key);
  1373. return self::$logs[$key];
  1374. }
  1375. /**
  1376. * Retrieves the queries logged on for given logging key.
  1377. *
  1378. * This method also ends logging for the specified key. To get the query log
  1379. * to date without ending the logger request the logging object by starting
  1380. * it again (which does nothing to an open log key) and call methods on it as
  1381. * desired.
  1382. *
  1383. * @param $logging_key
  1384. * The logging key to log.
  1385. * @param $key
  1386. * The database connection key for which we want to log.
  1387. *
  1388. * @return array
  1389. * The query log for the specified logging key and connection.
  1390. *
  1391. * @see DatabaseLog
  1392. */
  1393. final public static function getLog($logging_key, $key = 'default') {
  1394. if (empty(self::$logs[$key])) {
  1395. return NULL;
  1396. }
  1397. $queries = self::$logs[$key]->get($logging_key);
  1398. self::$logs[$key]->end($logging_key);
  1399. return $queries;
  1400. }
  1401. /**
  1402. * Gets the connection object for the specified database key and target.
  1403. *
  1404. * @param $target
  1405. * The database target name.
  1406. * @param $key
  1407. * The database connection key. Defaults to NULL which means the active key.
  1408. *
  1409. * @return DatabaseConnection
  1410. * The corresponding connection object.
  1411. */
  1412. final public static function getConnection($target = 'default', $key = NULL) {
  1413. if (!isset($key)) {
  1414. // By default, we want the active connection, set in setActiveConnection.
  1415. $key = self::$activeKey;
  1416. }
  1417. // If the requested target does not exist, or if it is ignored, we fall back
  1418. // to the default target. The target is typically either "default" or
  1419. // "slave", indicating to use a slave SQL server if one is available. If
  1420. // it's not available, then the default/master server is the correct server
  1421. // to use.
  1422. if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
  1423. $target = 'default';
  1424. }
  1425. if (!isset(self::$connections[$key][$target])) {
  1426. // If necessary, a new connection is opened.
  1427. self::$connections[$key][$target] = self::openConnection($key, $target);
  1428. }
  1429. return self::$connections[$key][$target];
  1430. }
  1431. /**
  1432. * Determines if there is an active connection.
  1433. *
  1434. * Note that this method will return FALSE if no connection has been
  1435. * established yet, even if one could be.
  1436. *
  1437. * @return
  1438. * TRUE if there is at least one database connection established, FALSE
  1439. * otherwise.
  1440. */
  1441. final public static function isActiveConnection() {
  1442. return !empty(self::$activeKey) && !empty(self::$connections) && !empty(self::$connections[self::$activeKey]);
  1443. }
  1444. /**
  1445. * Sets the active connection to the specified key.
  1446. *
  1447. * @return
  1448. * The previous database connection key.
  1449. */
  1450. final public static function setActiveConnection($key = 'default') {
  1451. if (empty(self::$databaseInfo)) {
  1452. self::parseConnectionInfo();
  1453. }
  1454. if (!empty(self::$databaseInfo[$key])) {
  1455. $old_key = self::$activeKey;
  1456. self::$activeKey = $key;
  1457. return $old_key;
  1458. }
  1459. }
  1460. /**
  1461. * Process the configuration file for database information.
  1462. */
  1463. final public static function parseConnectionInfo() {
  1464. global $databases;
  1465. $database_info = is_array($databases) ? $databases : array();
  1466. foreach ($database_info as $index => $info) {
  1467. foreach ($database_info[$index] as $target => $value) {
  1468. // If there is no "driver" property, then we assume it's an array of
  1469. // possible connections for this target. Pick one at random. That allows
  1470. // us to have, for example, multiple slave servers.
  1471. if (empty($value['driver'])) {
  1472. $database_info[$index][$target] = $database_info[$index][$target][mt_rand(0, count($database_info[$index][$target]) - 1)];
  1473. }
  1474. // Parse the prefix information.
  1475. if (!isset($database_info[$index][$target]['prefix'])) {
  1476. // Default to an empty prefix.
  1477. $database_info[$index][$target]['prefix'] = array(
  1478. 'default' => '',
  1479. );
  1480. }
  1481. elseif (!is_array($database_info[$index][$target]['prefix'])) {
  1482. // Transform the flat form into an array form.
  1483. $database_info[$index][$target]['prefix'] = array(
  1484. 'default' => $database_info[$index][$target]['prefix'],
  1485. );
  1486. }
  1487. }
  1488. }
  1489. if (!is_array(self::$databaseInfo)) {
  1490. self::$databaseInfo = $database_info;
  1491. }
  1492. // Merge the new $database_info into the existing.
  1493. // array_merge_recursive() cannot be used, as it would make multiple
  1494. // database, user, and password keys in the same database array.
  1495. else {
  1496. foreach ($database_info as $database_key => $database_values) {
  1497. foreach ($database_values as $target => $target_values) {
  1498. self::$databaseInfo[$database_key][$target] = $target_values;
  1499. }
  1500. }
  1501. }
  1502. }
  1503. /**
  1504. * Adds database connection information for a given key/target.
  1505. *
  1506. * This method allows the addition of new connection credentials at runtime.
  1507. * Under normal circumstances the preferred way to specify database
  1508. * credentials is via settings.php. However, this method allows them to be
  1509. * added at arbitrary times, such as during unit tests, when connecting to
  1510. * admin-defined third party databases, etc.
  1511. *
  1512. * If the given key/target pair already exists, this method will be ignored.
  1513. *
  1514. * @param $key
  1515. * The database key.
  1516. * @param $target
  1517. * The database target name.
  1518. * @param $info
  1519. * The database connection information, as it would be defined in
  1520. * settings.php. Note that the structure of this array will depend on the
  1521. * database driver it is connecting to.
  1522. */
  1523. public static function addConnectionInfo($key, $target, $info) {
  1524. if (empty(self::$databaseInfo[$key][$target])) {
  1525. self::$databaseInfo[$key][$target] = $info;
  1526. }
  1527. }
  1528. /**
  1529. * Gets information on the specified database connection.
  1530. *
  1531. * @param $connection
  1532. * The connection key for which we want information.
  1533. */
  1534. final public static function getConnectionInfo($key = 'default') {
  1535. if (empty(self::$databaseInfo)) {
  1536. self::parseConnectionInfo();
  1537. }
  1538. if (!empty(self::$databaseInfo[$key])) {
  1539. return self::$databaseInfo[$key];
  1540. }
  1541. }
  1542. /**
  1543. * Rename a connection and its corresponding connection information.
  1544. *
  1545. * @param $old_key
  1546. * The old connection key.
  1547. * @param $new_key
  1548. * The new connection key.
  1549. * @return
  1550. * TRUE in case of success, FALSE otherwise.
  1551. */
  1552. final public static function renameConnection($old_key, $new_key) {
  1553. if (empty(self::$databaseInfo)) {
  1554. self::parseConnectionInfo();
  1555. }
  1556. if (!empty(self::$databaseInfo[$old_key]) && empty(self::$databaseInfo[$new_key])) {
  1557. // Migrate the database connection information.
  1558. self::$databaseInfo[$new_key] = self::$databaseInfo[$old_key];
  1559. unset(self::$databaseInfo[$old_key]);
  1560. // Migrate over the DatabaseConnection object if it exists.
  1561. if (isset(self::$connections[$old_key])) {
  1562. self::$connections[$new_key] = self::$connections[$old_key];
  1563. unset(self::$connections[$old_key]);
  1564. }
  1565. return TRUE;
  1566. }
  1567. else {
  1568. return FALSE;
  1569. }
  1570. }
  1571. /**
  1572. * Remove a connection and its corresponding connection information.
  1573. *
  1574. * @param $key
  1575. * The connection key.
  1576. * @return
  1577. * TRUE in case of success, FALSE otherwise.
  1578. */
  1579. final public static function removeConnection($key) {
  1580. if (isset(self::$databaseInfo[$key])) {
  1581. self::closeConnection(NULL, $key);
  1582. unset(self::$databaseInfo[$key]);
  1583. return TRUE;
  1584. }
  1585. else {
  1586. return FALSE;
  1587. }
  1588. }
  1589. /**
  1590. * Opens a connection to the server specified by the given key and target.
  1591. *
  1592. * @param $key
  1593. * The database connection key, as specified in settings.php. The default is
  1594. * "default".
  1595. * @param $target
  1596. * The database target to open.
  1597. *
  1598. * @throws DatabaseConnectionNotDefinedException
  1599. * @throws DatabaseDriverNotSpecifiedException
  1600. */
  1601. final protected static function openConnection($key, $target) {
  1602. if (empty(self::$databaseInfo)) {
  1603. self::parseConnectionInfo();
  1604. }
  1605. // If the requested database does not exist then it is an unrecoverable
  1606. // error.
  1607. if (!isset(self::$databaseInfo[$key])) {
  1608. throw new DatabaseConnectionNotDefinedException('The specified database connection is not defined: ' . $key);
  1609. }
  1610. if (!$driver = self::$databaseInfo[$key][$target]['driver']) {
  1611. throw new DatabaseDriverNotSpecifiedException('Driver not specified for this database connection: ' . $key);
  1612. }
  1613. // We cannot rely on the registry yet, because the registry requires an
  1614. // open database connection.
  1615. $driver_class = 'DatabaseConnection_' . $driver;
  1616. require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
  1617. $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
  1618. $new_connection->setTarget($target);
  1619. $new_connection->setKey($key);
  1620. // If we have any active logging objects for this connection key, we need
  1621. // to associate them with the connection we just opened.
  1622. if (!empty(self::$logs[$key])) {
  1623. $new_connection->setLogger(self::$logs[$key]);
  1624. }
  1625. return $new_connection;
  1626. }
  1627. /**
  1628. * Closes a connection to the server specified by the given key and target.
  1629. *
  1630. * @param $target
  1631. * The database target name. Defaults to NULL meaning that all target
  1632. * connections will be closed.
  1633. * @param $key
  1634. * The database connection key. Defaults to NULL which means the active key.
  1635. */
  1636. public static function closeConnection($target = NULL, $key = NULL) {
  1637. // Gets the active connection by default.
  1638. if (!isset($key)) {
  1639. $key = self::$activeKey;
  1640. }
  1641. // To close a connection, it needs to be set to NULL and removed from the
  1642. // static variable. In all cases, closeConnection() might be called for a
  1643. // connection that was not opened yet, in which case the key is not defined
  1644. // yet and we just ensure that the connection key is undefined.
  1645. if (isset($target)) {
  1646. if (isset(self::$connections[$key][$target])) {
  1647. self::$connections[$key][$target]->destroy();
  1648. self::$connections[$key][$target] = NULL;
  1649. }
  1650. unset(self::$connections[$key][$target]);
  1651. }
  1652. else {
  1653. if (isset(self::$connections[$key])) {
  1654. foreach (self::$connections[$key] as $target => $connection) {
  1655. self::$connections[$key][$target]->destroy();
  1656. self::$connections[$key][$target] = NULL;
  1657. }
  1658. }
  1659. unset(self::$connections[$key]);
  1660. }
  1661. }
  1662. /**
  1663. * Instructs the system to temporarily ignore a given key/target.
  1664. *
  1665. * At times we need to temporarily disable slave queries. To do so, call this
  1666. * method with the database key and the target to disable. That database key
  1667. * will then always fall back to 'default' for that key, even if it's defined.
  1668. *
  1669. * @param $key
  1670. * The database connection key.
  1671. * @param $target
  1672. * The target of the specified key to ignore.
  1673. */
  1674. public static function ignoreTarget($key, $target) {
  1675. self::$ignoreTargets[$key][$target] = TRUE;
  1676. }
  1677. /**
  1678. * Load a file for the database that might hold a class.
  1679. *
  1680. * @param $driver
  1681. * The name of the driver.
  1682. * @param array $files
  1683. * The name of the files the driver specific class can be.
  1684. */
  1685. public static function loadDriverFile($driver, array $files = array()) {
  1686. static $base_path;
  1687. if (empty($base_path)) {
  1688. $base_path = dirname(realpath(__FILE__));
  1689. }
  1690. $driver_base_path = "$base_path/$driver";
  1691. foreach ($files as $file) {
  1692. // Load the base file first so that classes extending base classes will
  1693. // have the base class loaded.
  1694. foreach (array("$base_path/$file", "$driver_base_path/$file") as $filename) {
  1695. // The OS caches file_exists() and PHP caches require_once(), so
  1696. // we'll let both of those take care of performance here.
  1697. if (file_exists($filename)) {
  1698. require_once $filename;
  1699. }
  1700. }
  1701. }
  1702. }
  1703. }
  1704. /**
  1705. * Exception for when popTransaction() is called with no active transaction.
  1706. */
  1707. class DatabaseTransactionNoActiveException extends Exception { }
  1708. /**
  1709. * Exception thrown when a savepoint or transaction name occurs twice.
  1710. */
  1711. class DatabaseTransactionNameNonUniqueException extends Exception { }
  1712. /**
  1713. * Exception thrown when a commit() function fails.
  1714. */
  1715. class DatabaseTransactionCommitFailedException extends Exception { }
  1716. /**
  1717. * Exception to deny attempts to explicitly manage transactions.
  1718. *
  1719. * This exception will be thrown when the PDO connection commit() is called.
  1720. * Code should never call this method directly.
  1721. */
  1722. class DatabaseTransactionExplicitCommitNotAllowedException extends Exception { }
  1723. /**
  1724. * Exception thrown when a rollback() resulted in other active transactions being rolled-back.
  1725. */
  1726. class DatabaseTransactionOutOfOrderException extends Exception { }
  1727. /**
  1728. * Exception thrown for merge queries that do not make semantic sense.
  1729. *
  1730. * There are many ways that a merge query could be malformed. They should all
  1731. * throw this exception and set an appropriately descriptive message.
  1732. */
  1733. class InvalidMergeQueryException extends Exception {}
  1734. /**
  1735. * Exception thrown if an insert query specifies a field twice.
  1736. *
  1737. * It is not allowed to specify a field as default and insert field, this
  1738. * exception is thrown if that is the case.
  1739. */
  1740. class FieldsOverlapException extends Exception {}
  1741. /**
  1742. * Exception thrown if an insert query doesn't specify insert or default fields.
  1743. */
  1744. class NoFieldsException extends Exception {}
  1745. /**
  1746. * Exception thrown if an undefined database connection is requested.
  1747. */
  1748. class DatabaseConnectionNotDefinedException extends Exception {}
  1749. /**
  1750. * Exception thrown if no driver is specified for a database connection.
  1751. */
  1752. class DatabaseDriverNotSpecifiedException extends Exception {}
  1753. /**
  1754. * A wrapper class for creating and managing database transactions.
  1755. *
  1756. * Not all databases or database configurations support transactions. For
  1757. * example, MySQL MyISAM tables do not. It is also easy to begin a transaction
  1758. * and then forget to commit it, which can lead to connection errors when
  1759. * another transaction is started.
  1760. *
  1761. * This class acts as a wrapper for transactions. To begin a transaction,
  1762. * simply instantiate it. When the object goes out of scope and is destroyed
  1763. * it will automatically commit. It also will check to see if the specified
  1764. * connection supports transactions. If not, it will simply skip any transaction
  1765. * commands, allowing user-space code to proceed normally. The only difference
  1766. * is that rollbacks won't actually do anything.
  1767. *
  1768. * In the vast majority of cases, you should not instantiate this class
  1769. * directly. Instead, call ->startTransaction(), from the appropriate connection
  1770. * object.
  1771. */
  1772. class DatabaseTransaction {
  1773. /**
  1774. * The connection object for this transaction.
  1775. *
  1776. * @var DatabaseConnection
  1777. */
  1778. protected $connection;
  1779. /**
  1780. * A boolean value to indicate whether this transaction has been rolled back.
  1781. *
  1782. * @var Boolean
  1783. */
  1784. protected $rolledBack = FALSE;
  1785. /**
  1786. * The name of the transaction.
  1787. *
  1788. * This is used to label the transaction savepoint. It will be overridden to
  1789. * 'drupal_transaction' if there is no transaction depth.
  1790. */
  1791. protected $name;
  1792. public function __construct(DatabaseConnection $connection, $name = NULL) {
  1793. $this->connection = $connection;
  1794. // If there is no transaction depth, then no transaction has started. Name
  1795. // the transaction 'drupal_transaction'.
  1796. if (!$depth = $connection->transactionDepth()) {
  1797. $this->name = 'drupal_transaction';
  1798. }
  1799. // Within transactions, savepoints are used. Each savepoint requires a
  1800. // name. So if no name is present we need to create one.
  1801. elseif (!$name) {
  1802. $this->name = 'savepoint_' . $depth;
  1803. }
  1804. else {
  1805. $this->name = $name;
  1806. }
  1807. $this->connection->pushTransaction($this->name);
  1808. }
  1809. public function __destruct() {
  1810. // If we rolled back then the transaction would have already been popped.
  1811. if (!$this->rolledBack) {
  1812. $this->connection->popTransaction($this->name);
  1813. }
  1814. }
  1815. /**
  1816. * Retrieves the name of the transaction or savepoint.
  1817. */
  1818. public function name() {
  1819. return $this->name;
  1820. }
  1821. /**
  1822. * Rolls back the current transaction.
  1823. *
  1824. * This is just a wrapper method to rollback whatever transaction stack we are
  1825. * currently in, which is managed by the connection object itself. Note that
  1826. * logging (preferable with watchdog_exception()) needs to happen after a
  1827. * transaction has been rolled back or the log messages will be rolled back
  1828. * too.
  1829. *
  1830. * @see DatabaseConnection::rollback()
  1831. * @see watchdog_exception()
  1832. */
  1833. public function rollback() {
  1834. $this->rolledBack = TRUE;
  1835. $this->connection->rollback($this->name);
  1836. }
  1837. }
  1838. /**
  1839. * Represents a prepared statement.
  1840. *
  1841. * Some methods in that class are purposefully commented out. Due to a change in
  1842. * how PHP defines PDOStatement, we can't define a signature for those methods
  1843. * that will work the same way between versions older than 5.2.6 and later
  1844. * versions. See http://bugs.php.net/bug.php?id=42452 for more details.
  1845. *
  1846. * Child implementations should either extend PDOStatement:
  1847. * @code
  1848. * class DatabaseStatement_oracle extends PDOStatement implements DatabaseStatementInterface {}
  1849. * @endcode
  1850. * or define their own class. If defining their own class, they will also have
  1851. * to implement either the Iterator or IteratorAggregate interface before
  1852. * DatabaseStatementInterface:
  1853. * @code
  1854. * class DatabaseStatement_oracle implements Iterator, DatabaseStatementInterface {}
  1855. * @endcode
  1856. */
  1857. interface DatabaseStatementInterface extends Traversable {
  1858. /**
  1859. * Executes a prepared statement
  1860. *
  1861. * @param $args
  1862. * An array of values with as many elements as there are bound parameters in
  1863. * the SQL statement being executed.
  1864. * @param $options
  1865. * An array of options for this query.
  1866. *
  1867. * @return
  1868. * TRUE on success, or FALSE on failure.
  1869. */
  1870. public function execute($args = array(), $options = array());
  1871. /**
  1872. * Gets the query string of this statement.
  1873. *
  1874. * @return
  1875. * The query string, in its form with placeholders.
  1876. */
  1877. public function getQueryString();
  1878. /**
  1879. * Returns the number of rows affected by the last SQL statement.
  1880. *
  1881. * @return
  1882. * The number of rows affected by the last DELETE, INSERT, or UPDATE
  1883. * statement executed.
  1884. */
  1885. public function rowCount();
  1886. /**
  1887. * Sets the default fetch mode for this statement.
  1888. *
  1889. * See http://php.net/manual/pdo.constants.php for the definition of the
  1890. * constants used.
  1891. *
  1892. * @param $mode
  1893. * One of the PDO::FETCH_* constants.
  1894. * @param $a1
  1895. * An option depending of the fetch mode specified by $mode:
  1896. * - for PDO::FETCH_COLUMN, the index of the column to fetch
  1897. * - for PDO::FETCH_CLASS, the name of the class to create
  1898. * - for PDO::FETCH_INTO, the object to add the data to
  1899. * @param $a2
  1900. * If $mode is PDO::FETCH_CLASS, the optional arguments to pass to the
  1901. * constructor.
  1902. */
  1903. // public function setFetchMode($mode, $a1 = NULL, $a2 = array());
  1904. /**
  1905. * Fetches the next row from a result set.
  1906. *
  1907. * See http://php.net/manual/pdo.constants.php for the definition of the
  1908. * constants used.
  1909. *
  1910. * @param $mode
  1911. * One of the PDO::FETCH_* constants.
  1912. * Default to what was specified by setFetchMode().
  1913. * @param $cursor_orientation
  1914. * Not implemented in all database drivers, don't use.
  1915. * @param $cursor_offset
  1916. * Not implemented in all database drivers, don't use.
  1917. *
  1918. * @return
  1919. * A result, formatted according to $mode.
  1920. */
  1921. // public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL);
  1922. /**
  1923. * Returns a single field from the next record of a result set.
  1924. *
  1925. * @param $index
  1926. * The numeric index of the field to return. Defaults to the first field.
  1927. *
  1928. * @return
  1929. * A single field from the next record, or FALSE if there is no next record.
  1930. */
  1931. public function fetchField($index = 0);
  1932. /**
  1933. * Fetches the next row and returns it as an object.
  1934. *
  1935. * The object will be of the class specified by DatabaseStatementInterface::setFetchMode()
  1936. * or stdClass if not specified.
  1937. */
  1938. // public function fetchObject();
  1939. /**
  1940. * Fetches the next row and returns it as an associative array.
  1941. *
  1942. * This method corresponds to PDOStatement::fetchObject(), but for associative
  1943. * arrays. For some reason PDOStatement does not have a corresponding array
  1944. * helper method, so one is added.
  1945. *
  1946. * @return
  1947. * An associative array, or FALSE if there is no next row.
  1948. */
  1949. public function fetchAssoc();
  1950. /**
  1951. * Returns an array containing all of the result set rows.
  1952. *
  1953. * @param $mode
  1954. * One of the PDO::FETCH_* constants.
  1955. * @param $column_index
  1956. * If $mode is PDO::FETCH_COLUMN, the index of the column to fetch.
  1957. * @param $constructor_arguments
  1958. * If $mode is PDO::FETCH_CLASS, the arguments to pass to the constructor.
  1959. *
  1960. * @return
  1961. * An array of results.
  1962. */
  1963. // function fetchAll($mode = NULL, $column_index = NULL, array $constructor_arguments);
  1964. /**
  1965. * Returns an entire single column of a result set as an indexed array.
  1966. *
  1967. * Note that this method will run the result set to the end.
  1968. *
  1969. * @param $index
  1970. * The index of the column number to fetch.
  1971. *
  1972. * @return
  1973. * An indexed array, or an empty array if there is no result set.
  1974. */
  1975. public function fetchCol($index = 0);
  1976. /**
  1977. * Returns the entire result set as a single associative array.
  1978. *
  1979. * This method is only useful for two-column result sets. It will return an
  1980. * associative array where the key is one column from the result set and the
  1981. * value is another field. In most cases, the default of the first two columns
  1982. * is appropriate.
  1983. *
  1984. * Note that this method will run the result set to the end.
  1985. *
  1986. * @param $key_index
  1987. * The numeric index of the field to use as the array key.
  1988. * @param $value_index
  1989. * The numeric index of the field to use as the array value.
  1990. *
  1991. * @return
  1992. * An associative array, or an empty array if there is no result set.
  1993. */
  1994. public function fetchAllKeyed($key_index = 0, $value_index = 1);
  1995. /**
  1996. * Returns the result set as an associative array keyed by the given field.
  1997. *
  1998. * If the given key appears multiple times, later records will overwrite
  1999. * earlier ones.
  2000. *
  2001. * @param $key
  2002. * The name of the field on which to index the array.
  2003. * @param $fetch
  2004. * The fetchmode to use. If set to PDO::FETCH_ASSOC, PDO::FETCH_NUM, or
  2005. * PDO::FETCH_BOTH the returned value with be an array of arrays. For any
  2006. * other value it will be an array of objects. By default, the fetch mode
  2007. * set for the query will be used.
  2008. *
  2009. * @return
  2010. * An associative array, or an empty array if there is no result set.
  2011. */
  2012. public function fetchAllAssoc($key, $fetch = NULL);
  2013. }
  2014. /**
  2015. * Default implementation of DatabaseStatementInterface.
  2016. *
  2017. * PDO allows us to extend the PDOStatement class to provide additional
  2018. * functionality beyond that offered by default. We do need extra
  2019. * functionality. By default, this class is not driver-specific. If a given
  2020. * driver needs to set a custom statement class, it may do so in its
  2021. * constructor.
  2022. *
  2023. * @see http://us.php.net/pdostatement
  2024. */
  2025. class DatabaseStatementBase extends PDOStatement implements DatabaseStatementInterface {
  2026. /**
  2027. * Reference to the database connection object for this statement.
  2028. *
  2029. * The name $dbh is inherited from PDOStatement.
  2030. *
  2031. * @var DatabaseConnection
  2032. */
  2033. public $dbh;
  2034. protected function __construct($dbh) {
  2035. $this->dbh = $dbh;
  2036. $this->setFetchMode(PDO::FETCH_OBJ);
  2037. }
  2038. public function execute($args = array(), $options = array()) {
  2039. if (isset($options['fetch'])) {
  2040. if (is_string($options['fetch'])) {
  2041. // Default to an object. Note: db fields will be added to the object
  2042. // before the constructor is run. If you need to assign fields after
  2043. // the constructor is run, see http://drupal.org/node/315092.
  2044. $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
  2045. }
  2046. else {
  2047. $this->setFetchMode($options['fetch']);
  2048. }
  2049. }
  2050. $logger = $this->dbh->getLogger();
  2051. if (!empty($logger)) {
  2052. $query_start = microtime(TRUE);
  2053. }
  2054. $return = parent::execute($args);
  2055. if (!empty($logger)) {
  2056. $query_end = microtime(TRUE);
  2057. $logger->log($this, $args, $query_end - $query_start);
  2058. }
  2059. return $return;
  2060. }
  2061. public function getQueryString() {
  2062. return $this->queryString;
  2063. }
  2064. public function fetchCol($index = 0) {
  2065. return $this->fetchAll(PDO::FETCH_COLUMN, $index);
  2066. }
  2067. public function fetchAllAssoc($key, $fetch = NULL) {
  2068. $return = array();
  2069. if (isset($fetch)) {
  2070. if (is_string($fetch)) {
  2071. $this->setFetchMode(PDO::FETCH_CLASS, $fetch);
  2072. }
  2073. else {
  2074. $this->setFetchMode($fetch);
  2075. }
  2076. }
  2077. foreach ($this as $record) {
  2078. $record_key = is_object($record) ? $record->$key : $record[$key];
  2079. $return[$record_key] = $record;
  2080. }
  2081. return $return;
  2082. }
  2083. public function fetchAllKeyed($key_index = 0, $value_index = 1) {
  2084. $return = array();
  2085. $this->setFetchMode(PDO::FETCH_NUM);
  2086. foreach ($this as $record) {
  2087. $return[$record[$key_index]] = $record[$value_index];
  2088. }
  2089. return $return;
  2090. }
  2091. public function fetchField($index = 0) {
  2092. // Call PDOStatement::fetchColumn to fetch the field.
  2093. return $this->fetchColumn($index);
  2094. }
  2095. public function fetchAssoc() {
  2096. // Call PDOStatement::fetch to fetch the row.
  2097. return $this->fetch(PDO::FETCH_ASSOC);
  2098. }
  2099. }
  2100. /**
  2101. * Empty implementation of a database statement.
  2102. *
  2103. * This class satisfies the requirements of being a database statement/result
  2104. * object, but does not actually contain data. It is useful when developers
  2105. * need to safely return an "empty" result set without connecting to an actual
  2106. * database. Calling code can then treat it the same as if it were an actual
  2107. * result set that happens to contain no records.
  2108. *
  2109. * @see SearchQuery
  2110. */
  2111. class DatabaseStatementEmpty implements Iterator, DatabaseStatementInterface {
  2112. public function execute($args = array(), $options = array()) {
  2113. return FALSE;
  2114. }
  2115. public function getQueryString() {
  2116. return '';
  2117. }
  2118. public function rowCount() {
  2119. return 0;
  2120. }
  2121. public function setFetchMode($mode, $a1 = NULL, $a2 = array()) {
  2122. return;
  2123. }
  2124. public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL) {
  2125. return NULL;
  2126. }
  2127. public function fetchField($index = 0) {
  2128. return NULL;
  2129. }
  2130. public function fetchObject() {
  2131. return NULL;
  2132. }
  2133. public function fetchAssoc() {
  2134. return NULL;
  2135. }
  2136. function fetchAll($mode = NULL, $column_index = NULL, array $constructor_arguments = array()) {
  2137. return array();
  2138. }
  2139. public function fetchCol($index = 0) {
  2140. return array();
  2141. }
  2142. public function fetchAllKeyed($key_index = 0, $value_index = 1) {
  2143. return array();
  2144. }
  2145. public function fetchAllAssoc($key, $fetch = NULL) {
  2146. return array();
  2147. }
  2148. /* Implementations of Iterator. */
  2149. public function current() {
  2150. return NULL;
  2151. }
  2152. public function key() {
  2153. return NULL;
  2154. }
  2155. public function rewind() {
  2156. // Nothing to do: our DatabaseStatement can't be rewound.
  2157. }
  2158. public function next() {
  2159. // Do nothing, since this is an always-empty implementation.
  2160. }
  2161. public function valid() {
  2162. return FALSE;
  2163. }
  2164. }
  2165. /**
  2166. * The following utility functions are simply convenience wrappers.
  2167. *
  2168. * They should never, ever have any database-specific code in them.
  2169. */
  2170. /**
  2171. * Executes an arbitrary query string against the active database.
  2172. *
  2173. * Use this function for SELECT queries if it is just a simple query string.
  2174. * If the caller or other modules need to change the query, use db_select()
  2175. * instead.
  2176. *
  2177. * Do not use this function for INSERT, UPDATE, or DELETE queries. Those should
  2178. * be handled via db_insert(), db_update() and db_delete() respectively.
  2179. *
  2180. * @param $query
  2181. * The prepared statement query to run. Although it will accept both named and
  2182. * unnamed placeholders, named placeholders are strongly preferred as they are
  2183. * more self-documenting.
  2184. * @param $args
  2185. * An array of values to substitute into the query. If the query uses named
  2186. * placeholders, this is an associative array in any order. If the query uses
  2187. * unnamed placeholders (?), this is an indexed array and the order must match
  2188. * the order of placeholders in the query string.
  2189. * @param $options
  2190. * An array of options to control how the query operates.
  2191. *
  2192. * @return DatabaseStatementInterface
  2193. * A prepared statement object, already executed.
  2194. *
  2195. * @see DatabaseConnection::defaultOptions()
  2196. */
  2197. function db_query($query, array $args = array(), array $options = array()) {
  2198. if (empty($options['target'])) {
  2199. $options['target'] = 'default';
  2200. }
  2201. return Database::getConnection($options['target'])->query($query, $args, $options);
  2202. }
  2203. /**
  2204. * Executes a query against the active database, restricted to a range.
  2205. *
  2206. * @param $query
  2207. * The prepared statement query to run. Although it will accept both named and
  2208. * unnamed placeholders, named placeholders are strongly preferred as they are
  2209. * more self-documenting.
  2210. * @param $from
  2211. * The first record from the result set to return.
  2212. * @param $count
  2213. * The number of records to return from the result set.
  2214. * @param $args
  2215. * An array of values to substitute into the query. If the query uses named
  2216. * placeholders, this is an associative array in any order. If the query uses
  2217. * unnamed placeholders (?), this is an indexed array and the order must match
  2218. * the order of placeholders in the query string.
  2219. * @param $options
  2220. * An array of options to control how the query operates.
  2221. *
  2222. * @return DatabaseStatementInterface
  2223. * A prepared statement object, already executed.
  2224. *
  2225. * @see DatabaseConnection::defaultOptions()
  2226. */
  2227. function db_query_range($query, $from, $count, array $args = array(), array $options = array()) {
  2228. if (empty($options['target'])) {
  2229. $options['target'] = 'default';
  2230. }
  2231. return Database::getConnection($options['target'])->queryRange($query, $from, $count, $args, $options);
  2232. }
  2233. /**
  2234. * Executes a SELECT query string and saves the result set to a temporary table.
  2235. *
  2236. * The execution of the query string happens against the active database.
  2237. *
  2238. * @param $query
  2239. * The prepared SELECT statement query to run. Although it will accept both
  2240. * named and unnamed placeholders, named placeholders are strongly preferred
  2241. * as they are more self-documenting.
  2242. * @param $args
  2243. * An array of values to substitute into the query. If the query uses named
  2244. * placeholders, this is an associative array in any order. If the query uses
  2245. * unnamed placeholders (?), this is an indexed array and the order must match
  2246. * the order of placeholders in the query string.
  2247. * @param $options
  2248. * An array of options to control how the query operates.
  2249. *
  2250. * @return
  2251. * The name of the temporary table.
  2252. *
  2253. * @see DatabaseConnection::defaultOptions()
  2254. */
  2255. function db_query_temporary($query, array $args = array(), array $options = array()) {
  2256. if (empty($options['target'])) {
  2257. $options['target'] = 'default';
  2258. }
  2259. return Database::getConnection($options['target'])->queryTemporary($query, $args, $options);
  2260. }
  2261. /**
  2262. * Returns a new InsertQuery object for the active database.
  2263. *
  2264. * @param $table
  2265. * The table into which to insert.
  2266. * @param $options
  2267. * An array of options to control how the query operates.
  2268. *
  2269. * @return InsertQuery
  2270. * A new InsertQuery object for this connection.
  2271. */
  2272. function db_insert($table, array $options = array()) {
  2273. if (empty($options['target']) || $options['target'] == 'slave') {
  2274. $options['target'] = 'default';
  2275. }
  2276. return Database::getConnection($options['target'])->insert($table, $options);
  2277. }
  2278. /**
  2279. * Returns a new MergeQuery object for the active database.
  2280. *
  2281. * @param $table
  2282. * The table into which to merge.
  2283. * @param $options
  2284. * An array of options to control how the query operates.
  2285. *
  2286. * @return MergeQuery
  2287. * A new MergeQuery object for this connection.
  2288. */
  2289. function db_merge($table, array $options = array()) {
  2290. if (empty($options['target']) || $options['target'] == 'slave') {
  2291. $options['target'] = 'default';
  2292. }
  2293. return Database::getConnection($options['target'])->merge($table, $options);
  2294. }
  2295. /**
  2296. * Returns a new UpdateQuery object for the active database.
  2297. *
  2298. * @param $table
  2299. * The table to update.
  2300. * @param $options
  2301. * An array of options to control how the query operates.
  2302. *
  2303. * @return UpdateQuery
  2304. * A new UpdateQuery object for this connection.
  2305. */
  2306. function db_update($table, array $options = array()) {
  2307. if (empty($options['target']) || $options['target'] == 'slave') {
  2308. $options['target'] = 'default';
  2309. }
  2310. return Database::getConnection($options['target'])->update($table, $options);
  2311. }
  2312. /**
  2313. * Returns a new DeleteQuery object for the active database.
  2314. *
  2315. * @param $table
  2316. * The table from which to delete.
  2317. * @param $options
  2318. * An array of options to control how the query operates.
  2319. *
  2320. * @return DeleteQuery
  2321. * A new DeleteQuery object for this connection.
  2322. */
  2323. function db_delete($table, array $options = array()) {
  2324. if (empty($options['target']) || $options['target'] == 'slave') {
  2325. $options['target'] = 'default';
  2326. }
  2327. return Database::getConnection($options['target'])->delete($table, $options);
  2328. }
  2329. /**
  2330. * Returns a new TruncateQuery object for the active database.
  2331. *
  2332. * @param $table
  2333. * The table from which to delete.
  2334. * @param $options
  2335. * An array of options to control how the query operates.
  2336. *
  2337. * @return TruncateQuery
  2338. * A new TruncateQuery object for this connection.
  2339. */
  2340. function db_truncate($table, array $options = array()) {
  2341. if (empty($options['target']) || $options['target'] == 'slave') {
  2342. $options['target'] = 'default';
  2343. }
  2344. return Database::getConnection($options['target'])->truncate($table, $options);
  2345. }
  2346. /**
  2347. * Returns a new SelectQuery object for the active database.
  2348. *
  2349. * @param $table
  2350. * The base table for this query. May be a string or another SelectQuery
  2351. * object. If a query object is passed, it will be used as a subselect.
  2352. * @param $alias
  2353. * The alias for the base table of this query.
  2354. * @param $options
  2355. * An array of options to control how the query operates.
  2356. *
  2357. * @return SelectQuery
  2358. * A new SelectQuery object for this connection.
  2359. */
  2360. function db_select($table, $alias = NULL, array $options = array()) {
  2361. if (empty($options['target'])) {
  2362. $options['target'] = 'default';
  2363. }
  2364. return Database::getConnection($options['target'])->select($table, $alias, $options);
  2365. }
  2366. /**
  2367. * Returns a new transaction object for the active database.
  2368. *
  2369. * @param string $name
  2370. * Optional name of the transaction.
  2371. * @param array $options
  2372. * An array of options to control how the transaction operates:
  2373. * - target: The database target name.
  2374. *
  2375. * @return DatabaseTransaction
  2376. * A new DatabaseTransaction object for this connection.
  2377. */
  2378. function db_transaction($name = NULL, array $options = array()) {
  2379. if (empty($options['target'])) {
  2380. $options['target'] = 'default';
  2381. }
  2382. return Database::getConnection($options['target'])->startTransaction($name);
  2383. }
  2384. /**
  2385. * Sets a new active database.
  2386. *
  2387. * @param $key
  2388. * The key in the $databases array to set as the default database.
  2389. *
  2390. * @return
  2391. * The key of the formerly active database.
  2392. */
  2393. function db_set_active($key = 'default') {
  2394. return Database::setActiveConnection($key);
  2395. }
  2396. /**
  2397. * Restricts a dynamic table name to safe characters.
  2398. *
  2399. * Only keeps alphanumeric and underscores.
  2400. *
  2401. * @param $table
  2402. * The table name to escape.
  2403. *
  2404. * @return
  2405. * The escaped table name as a string.
  2406. */
  2407. function db_escape_table($table) {
  2408. return Database::getConnection()->escapeTable($table);
  2409. }
  2410. /**
  2411. * Restricts a dynamic column or constraint name to safe characters.
  2412. *
  2413. * Only keeps alphanumeric and underscores.
  2414. *
  2415. * @param $field
  2416. * The field name to escape.
  2417. *
  2418. * @return
  2419. * The escaped field name as a string.
  2420. */
  2421. function db_escape_field($field) {
  2422. return Database::getConnection()->escapeField($field);
  2423. }
  2424. /**
  2425. * Escapes characters that work as wildcard characters in a LIKE pattern.
  2426. *
  2427. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  2428. * a backslash. Use this to do a search for a verbatim string without any
  2429. * wildcard behavior.
  2430. *
  2431. * For example, the following does a case-insensitive query for all rows whose
  2432. * name starts with $prefix:
  2433. * @code
  2434. * $result = db_query(
  2435. * 'SELECT * FROM person WHERE name LIKE :pattern',
  2436. * array(':pattern' => db_like($prefix) . '%')
  2437. * );
  2438. * @endcode
  2439. *
  2440. * Backslash is defined as escape character for LIKE patterns in
  2441. * DatabaseCondition::mapConditionOperator().
  2442. *
  2443. * @param $string
  2444. * The string to escape.
  2445. *
  2446. * @return
  2447. * The escaped string.
  2448. */
  2449. function db_like($string) {
  2450. return Database::getConnection()->escapeLike($string);
  2451. }
  2452. /**
  2453. * Retrieves the name of the currently active database driver.
  2454. *
  2455. * @return
  2456. * The name of the currently active database driver.
  2457. */
  2458. function db_driver() {
  2459. return Database::getConnection()->driver();
  2460. }
  2461. /**
  2462. * Closes the active database connection.
  2463. *
  2464. * @param $options
  2465. * An array of options to control which connection is closed. Only the target
  2466. * key has any meaning in this case.
  2467. */
  2468. function db_close(array $options = array()) {
  2469. if (empty($options['target'])) {
  2470. $options['target'] = NULL;
  2471. }
  2472. Database::closeConnection($options['target']);
  2473. }
  2474. /**
  2475. * Retrieves a unique id.
  2476. *
  2477. * Use this function if for some reason you can't use a serial field. Using a
  2478. * serial field is preferred, and InsertQuery::execute() returns the value of
  2479. * the last ID inserted.
  2480. *
  2481. * @param $existing_id
  2482. * After a database import, it might be that the sequences table is behind, so
  2483. * by passing in a minimum ID, it can be assured that we never issue the same
  2484. * ID.
  2485. *
  2486. * @return
  2487. * An integer number larger than any number returned before for this sequence.
  2488. */
  2489. function db_next_id($existing_id = 0) {
  2490. return Database::getConnection()->nextId($existing_id);
  2491. }
  2492. /**
  2493. * Returns a new DatabaseCondition, set to "OR" all conditions together.
  2494. *
  2495. * @return DatabaseCondition
  2496. */
  2497. function db_or() {
  2498. return new DatabaseCondition('OR');
  2499. }
  2500. /**
  2501. * Returns a new DatabaseCondition, set to "AND" all conditions together.
  2502. *
  2503. * @return DatabaseCondition
  2504. */
  2505. function db_and() {
  2506. return new DatabaseCondition('AND');
  2507. }
  2508. /**
  2509. * Returns a new DatabaseCondition, set to "XOR" all conditions together.
  2510. *
  2511. * @return DatabaseCondition
  2512. */
  2513. function db_xor() {
  2514. return new DatabaseCondition('XOR');
  2515. }
  2516. /**
  2517. * Returns a new DatabaseCondition, set to the specified conjunction.
  2518. *
  2519. * Internal API function call. The db_and(), db_or(), and db_xor()
  2520. * functions are preferred.
  2521. *
  2522. * @param $conjunction
  2523. * The conjunction to use for query conditions (AND, OR or XOR).
  2524. * @return DatabaseCondition
  2525. */
  2526. function db_condition($conjunction) {
  2527. return new DatabaseCondition($conjunction);
  2528. }
  2529. /**
  2530. * @} End of "defgroup database".
  2531. */
  2532. /**
  2533. * @addtogroup schemaapi
  2534. * @{
  2535. */
  2536. /**
  2537. * Creates a new table from a Drupal table definition.
  2538. *
  2539. * @param $name
  2540. * The name of the table to create.
  2541. * @param $table
  2542. * A Schema API table definition array.
  2543. */
  2544. function db_create_table($name, $table) {
  2545. return Database::getConnection()->schema()->createTable($name, $table);
  2546. }
  2547. /**
  2548. * Returns an array of field names from an array of key/index column specifiers.
  2549. *
  2550. * This is usually an identity function but if a key/index uses a column prefix
  2551. * specification, this function extracts just the name.
  2552. *
  2553. * @param $fields
  2554. * An array of key/index column specifiers.
  2555. *
  2556. * @return
  2557. * An array of field names.
  2558. */
  2559. function db_field_names($fields) {
  2560. return Database::getConnection()->schema()->fieldNames($fields);
  2561. }
  2562. /**
  2563. * Checks if an index exists in the given table.
  2564. *
  2565. * @param $table
  2566. * The name of the table in drupal (no prefixing).
  2567. * @param $name
  2568. * The name of the index in drupal (no prefixing).
  2569. *
  2570. * @return
  2571. * TRUE if the given index exists, otherwise FALSE.
  2572. */
  2573. function db_index_exists($table, $name) {
  2574. return Database::getConnection()->schema()->indexExists($table, $name);
  2575. }
  2576. /**
  2577. * Checks if a table exists.
  2578. *
  2579. * @param $table
  2580. * The name of the table in drupal (no prefixing).
  2581. *
  2582. * @return
  2583. * TRUE if the given table exists, otherwise FALSE.
  2584. */
  2585. function db_table_exists($table) {
  2586. return Database::getConnection()->schema()->tableExists($table);
  2587. }
  2588. /**
  2589. * Checks if a column exists in the given table.
  2590. *
  2591. * @param $table
  2592. * The name of the table in drupal (no prefixing).
  2593. * @param $field
  2594. * The name of the field.
  2595. *
  2596. * @return
  2597. * TRUE if the given column exists, otherwise FALSE.
  2598. */
  2599. function db_field_exists($table, $field) {
  2600. return Database::getConnection()->schema()->fieldExists($table, $field);
  2601. }
  2602. /**
  2603. * Finds all tables that are like the specified base table name.
  2604. *
  2605. * @param $table_expression
  2606. * An SQL expression, for example "simpletest%" (without the quotes).
  2607. * BEWARE: this is not prefixed, the caller should take care of that.
  2608. *
  2609. * @return
  2610. * Array, both the keys and the values are the matching tables.
  2611. */
  2612. function db_find_tables($table_expression) {
  2613. return Database::getConnection()->schema()->findTables($table_expression);
  2614. }
  2615. function _db_create_keys_sql($spec) {
  2616. return Database::getConnection()->schema()->createKeysSql($spec);
  2617. }
  2618. /**
  2619. * Renames a table.
  2620. *
  2621. * @param $table
  2622. * The current name of the table to be renamed.
  2623. * @param $new_name
  2624. * The new name for the table.
  2625. */
  2626. function db_rename_table($table, $new_name) {
  2627. return Database::getConnection()->schema()->renameTable($table, $new_name);
  2628. }
  2629. /**
  2630. * Drops a table.
  2631. *
  2632. * @param $table
  2633. * The table to be dropped.
  2634. */
  2635. function db_drop_table($table) {
  2636. return Database::getConnection()->schema()->dropTable($table);
  2637. }
  2638. /**
  2639. * Adds a new field to a table.
  2640. *
  2641. * @param $table
  2642. * Name of the table to be altered.
  2643. * @param $field
  2644. * Name of the field to be added.
  2645. * @param $spec
  2646. * The field specification array, as taken from a schema definition. The
  2647. * specification may also contain the key 'initial'; the newly-created field
  2648. * will be set to the value of the key in all rows. This is most useful for
  2649. * creating NOT NULL columns with no default value in existing tables.
  2650. * @param $keys_new
  2651. * (optional) Keys and indexes specification to be created on the table along
  2652. * with adding the field. The format is the same as a table specification, but
  2653. * without the 'fields' element. If you are adding a type 'serial' field, you
  2654. * MUST specify at least one key or index including it in this array. See
  2655. * db_change_field() for more explanation why.
  2656. *
  2657. * @see db_change_field()
  2658. */
  2659. function db_add_field($table, $field, $spec, $keys_new = array()) {
  2660. return Database::getConnection()->schema()->addField($table, $field, $spec, $keys_new);
  2661. }
  2662. /**
  2663. * Drops a field.
  2664. *
  2665. * @param $table
  2666. * The table to be altered.
  2667. * @param $field
  2668. * The field to be dropped.
  2669. */
  2670. function db_drop_field($table, $field) {
  2671. return Database::getConnection()->schema()->dropField($table, $field);
  2672. }
  2673. /**
  2674. * Sets the default value for a field.
  2675. *
  2676. * @param $table
  2677. * The table to be altered.
  2678. * @param $field
  2679. * The field to be altered.
  2680. * @param $default
  2681. * Default value to be set. NULL for 'default NULL'.
  2682. */
  2683. function db_field_set_default($table, $field, $default) {
  2684. return Database::getConnection()->schema()->fieldSetDefault($table, $field, $default);
  2685. }
  2686. /**
  2687. * Sets a field to have no default value.
  2688. *
  2689. * @param $table
  2690. * The table to be altered.
  2691. * @param $field
  2692. * The field to be altered.
  2693. */
  2694. function db_field_set_no_default($table, $field) {
  2695. return Database::getConnection()->schema()->fieldSetNoDefault($table, $field);
  2696. }
  2697. /**
  2698. * Adds a primary key to a database table.
  2699. *
  2700. * @param $table
  2701. * Name of the table to be altered.
  2702. * @param $fields
  2703. * Array of fields for the primary key.
  2704. */
  2705. function db_add_primary_key($table, $fields) {
  2706. return Database::getConnection()->schema()->addPrimaryKey($table, $fields);
  2707. }
  2708. /**
  2709. * Drops the primary key of a database table.
  2710. *
  2711. * @param $table
  2712. * Name of the table to be altered.
  2713. */
  2714. function db_drop_primary_key($table) {
  2715. return Database::getConnection()->schema()->dropPrimaryKey($table);
  2716. }
  2717. /**
  2718. * Adds a unique key.
  2719. *
  2720. * @param $table
  2721. * The table to be altered.
  2722. * @param $name
  2723. * The name of the key.
  2724. * @param $fields
  2725. * An array of field names.
  2726. */
  2727. function db_add_unique_key($table, $name, $fields) {
  2728. return Database::getConnection()->schema()->addUniqueKey($table, $name, $fields);
  2729. }
  2730. /**
  2731. * Drops a unique key.
  2732. *
  2733. * @param $table
  2734. * The table to be altered.
  2735. * @param $name
  2736. * The name of the key.
  2737. */
  2738. function db_drop_unique_key($table, $name) {
  2739. return Database::getConnection()->schema()->dropUniqueKey($table, $name);
  2740. }
  2741. /**
  2742. * Adds an index.
  2743. *
  2744. * @param $table
  2745. * The table to be altered.
  2746. * @param $name
  2747. * The name of the index.
  2748. * @param $fields
  2749. * An array of field names.
  2750. */
  2751. function db_add_index($table, $name, $fields) {
  2752. return Database::getConnection()->schema()->addIndex($table, $name, $fields);
  2753. }
  2754. /**
  2755. * Drops an index.
  2756. *
  2757. * @param $table
  2758. * The table to be altered.
  2759. * @param $name
  2760. * The name of the index.
  2761. */
  2762. function db_drop_index($table, $name) {
  2763. return Database::getConnection()->schema()->dropIndex($table, $name);
  2764. }
  2765. /**
  2766. * Changes a field definition.
  2767. *
  2768. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  2769. * recreate all indices and primary keys that are using the changed field.
  2770. *
  2771. * That means that you have to drop all affected keys and indexes with
  2772. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  2773. * To recreate the keys and indices, pass the key definitions as the optional
  2774. * $keys_new argument directly to db_change_field().
  2775. *
  2776. * For example, suppose you have:
  2777. * @code
  2778. * $schema['foo'] = array(
  2779. * 'fields' => array(
  2780. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  2781. * ),
  2782. * 'primary key' => array('bar')
  2783. * );
  2784. * @endcode
  2785. * and you want to change foo.bar to be type serial, leaving it as the primary
  2786. * key. The correct sequence is:
  2787. * @code
  2788. * db_drop_primary_key('foo');
  2789. * db_change_field('foo', 'bar', 'bar',
  2790. * array('type' => 'serial', 'not null' => TRUE),
  2791. * array('primary key' => array('bar')));
  2792. * @endcode
  2793. *
  2794. * The reasons for this are due to the different database engines:
  2795. *
  2796. * On PostgreSQL, changing a field definition involves adding a new field and
  2797. * dropping an old one which causes any indices, primary keys and sequences
  2798. * (from serial-type fields) that use the changed field to be dropped.
  2799. *
  2800. * On MySQL, all type 'serial' fields must be part of at least one key or index
  2801. * as soon as they are created. You cannot use
  2802. * db_add_{primary_key,unique_key,index}() for this purpose because the ALTER
  2803. * TABLE command will fail to add the column without a key or index
  2804. * specification. The solution is to use the optional $keys_new argument to
  2805. * create the key or index at the same time as field.
  2806. *
  2807. * You could use db_add_{primary_key,unique_key,index}() in all cases unless you
  2808. * are converting a field to be type serial. You can use the $keys_new argument
  2809. * in all cases.
  2810. *
  2811. * @param $table
  2812. * Name of the table.
  2813. * @param $field
  2814. * Name of the field to change.
  2815. * @param $field_new
  2816. * New name for the field (set to the same as $field if you don't want to
  2817. * change the name).
  2818. * @param $spec
  2819. * The field specification for the new field.
  2820. * @param $keys_new
  2821. * (optional) Keys and indexes specification to be created on the table along
  2822. * with changing the field. The format is the same as a table specification
  2823. * but without the 'fields' element.
  2824. */
  2825. function db_change_field($table, $field, $field_new, $spec, $keys_new = array()) {
  2826. return Database::getConnection()->schema()->changeField($table, $field, $field_new, $spec, $keys_new);
  2827. }
  2828. /**
  2829. * @} End of "addtogroup schemaapi".
  2830. */
  2831. /**
  2832. * Sets a session variable specifying the lag time for ignoring a slave server.
  2833. */
  2834. function db_ignore_slave() {
  2835. $connection_info = Database::getConnectionInfo();
  2836. // Only set ignore_slave_server if there are slave servers being used, which
  2837. // is assumed if there are more than one.
  2838. if (count($connection_info) > 1) {
  2839. // Five minutes is long enough to allow the slave to break and resume
  2840. // interrupted replication without causing problems on the Drupal site from
  2841. // the old data.
  2842. $duration = variable_get('maximum_replication_lag', 300);
  2843. // Set session variable with amount of time to delay before using slave.
  2844. $_SESSION['ignore_slave_server'] = REQUEST_TIME + $duration;
  2845. }
  2846. }