database.inc 97 KB

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