database.inc 94 KB

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