database.inc 92 KB

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