database.inc 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165
  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->query_string = $stmt->getQueryString();
  715. }
  716. else {
  717. $e->query_string = $query;
  718. }
  719. $e->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 insert query specifies a field twice.
  1782. *
  1783. * It is not allowed to specify a field as default and insert field, this
  1784. * exception is thrown if that is the case.
  1785. */
  1786. class FieldsOverlapException extends Exception {}
  1787. /**
  1788. * Exception thrown if an insert query doesn't specify insert or default fields.
  1789. */
  1790. class NoFieldsException extends Exception {}
  1791. /**
  1792. * Exception thrown if an undefined database connection is requested.
  1793. */
  1794. class DatabaseConnectionNotDefinedException extends Exception {}
  1795. /**
  1796. * Exception thrown if no driver is specified for a database connection.
  1797. */
  1798. class DatabaseDriverNotSpecifiedException extends Exception {}
  1799. /**
  1800. * A wrapper class for creating and managing database transactions.
  1801. *
  1802. * Not all databases or database configurations support transactions. For
  1803. * example, MySQL MyISAM tables do not. It is also easy to begin a transaction
  1804. * and then forget to commit it, which can lead to connection errors when
  1805. * another transaction is started.
  1806. *
  1807. * This class acts as a wrapper for transactions. To begin a transaction,
  1808. * simply instantiate it. When the object goes out of scope and is destroyed
  1809. * it will automatically commit. It also will check to see if the specified
  1810. * connection supports transactions. If not, it will simply skip any transaction
  1811. * commands, allowing user-space code to proceed normally. The only difference
  1812. * is that rollbacks won't actually do anything.
  1813. *
  1814. * In the vast majority of cases, you should not instantiate this class
  1815. * directly. Instead, call ->startTransaction(), from the appropriate connection
  1816. * object.
  1817. */
  1818. class DatabaseTransaction {
  1819. /**
  1820. * The connection object for this transaction.
  1821. *
  1822. * @var DatabaseConnection
  1823. */
  1824. protected $connection;
  1825. /**
  1826. * A boolean value to indicate whether this transaction has been rolled back.
  1827. *
  1828. * @var Boolean
  1829. */
  1830. protected $rolledBack = FALSE;
  1831. /**
  1832. * The name of the transaction.
  1833. *
  1834. * This is used to label the transaction savepoint. It will be overridden to
  1835. * 'drupal_transaction' if there is no transaction depth.
  1836. */
  1837. protected $name;
  1838. public function __construct(DatabaseConnection $connection, $name = NULL) {
  1839. $this->connection = $connection;
  1840. // If there is no transaction depth, then no transaction has started. Name
  1841. // the transaction 'drupal_transaction'.
  1842. if (!$depth = $connection->transactionDepth()) {
  1843. $this->name = 'drupal_transaction';
  1844. }
  1845. // Within transactions, savepoints are used. Each savepoint requires a
  1846. // name. So if no name is present we need to create one.
  1847. elseif (!$name) {
  1848. $this->name = 'savepoint_' . $depth;
  1849. }
  1850. else {
  1851. $this->name = $name;
  1852. }
  1853. $this->connection->pushTransaction($this->name);
  1854. }
  1855. public function __destruct() {
  1856. // If we rolled back then the transaction would have already been popped.
  1857. if (!$this->rolledBack) {
  1858. $this->connection->popTransaction($this->name);
  1859. }
  1860. }
  1861. /**
  1862. * Retrieves the name of the transaction or savepoint.
  1863. */
  1864. public function name() {
  1865. return $this->name;
  1866. }
  1867. /**
  1868. * Rolls back the current transaction.
  1869. *
  1870. * This is just a wrapper method to rollback whatever transaction stack we are
  1871. * currently in, which is managed by the connection object itself. Note that
  1872. * logging (preferable with watchdog_exception()) needs to happen after a
  1873. * transaction has been rolled back or the log messages will be rolled back
  1874. * too.
  1875. *
  1876. * @see DatabaseConnection::rollback()
  1877. * @see watchdog_exception()
  1878. */
  1879. public function rollback() {
  1880. $this->rolledBack = TRUE;
  1881. $this->connection->rollback($this->name);
  1882. }
  1883. }
  1884. /**
  1885. * Represents a prepared statement.
  1886. *
  1887. * Some methods in that class are purposefully commented out. Due to a change in
  1888. * how PHP defines PDOStatement, we can't define a signature for those methods
  1889. * that will work the same way between versions older than 5.2.6 and later
  1890. * versions. See http://bugs.php.net/bug.php?id=42452 for more details.
  1891. *
  1892. * Child implementations should either extend PDOStatement:
  1893. * @code
  1894. * class DatabaseStatement_oracle extends PDOStatement implements DatabaseStatementInterface {}
  1895. * @endcode
  1896. * or define their own class. If defining their own class, they will also have
  1897. * to implement either the Iterator or IteratorAggregate interface before
  1898. * DatabaseStatementInterface:
  1899. * @code
  1900. * class DatabaseStatement_oracle implements Iterator, DatabaseStatementInterface {}
  1901. * @endcode
  1902. */
  1903. interface DatabaseStatementInterface extends Traversable {
  1904. /**
  1905. * Executes a prepared statement
  1906. *
  1907. * @param $args
  1908. * An array of values with as many elements as there are bound parameters in
  1909. * the SQL statement being executed.
  1910. * @param $options
  1911. * An array of options for this query.
  1912. *
  1913. * @return
  1914. * TRUE on success, or FALSE on failure.
  1915. */
  1916. public function execute($args = array(), $options = array());
  1917. /**
  1918. * Gets the query string of this statement.
  1919. *
  1920. * @return
  1921. * The query string, in its form with placeholders.
  1922. */
  1923. public function getQueryString();
  1924. /**
  1925. * Returns the number of rows affected by the last SQL statement.
  1926. *
  1927. * @return
  1928. * The number of rows affected by the last DELETE, INSERT, or UPDATE
  1929. * statement executed.
  1930. */
  1931. public function rowCount();
  1932. /**
  1933. * Sets the default fetch mode for this statement.
  1934. *
  1935. * See http://php.net/manual/pdo.constants.php for the definition of the
  1936. * constants used.
  1937. *
  1938. * @param $mode
  1939. * One of the PDO::FETCH_* constants.
  1940. * @param $a1
  1941. * An option depending of the fetch mode specified by $mode:
  1942. * - for PDO::FETCH_COLUMN, the index of the column to fetch
  1943. * - for PDO::FETCH_CLASS, the name of the class to create
  1944. * - for PDO::FETCH_INTO, the object to add the data to
  1945. * @param $a2
  1946. * If $mode is PDO::FETCH_CLASS, the optional arguments to pass to the
  1947. * constructor.
  1948. */
  1949. // public function setFetchMode($mode, $a1 = NULL, $a2 = array());
  1950. /**
  1951. * Fetches the next row from a result set.
  1952. *
  1953. * See http://php.net/manual/pdo.constants.php for the definition of the
  1954. * constants used.
  1955. *
  1956. * @param $mode
  1957. * One of the PDO::FETCH_* constants.
  1958. * Default to what was specified by setFetchMode().
  1959. * @param $cursor_orientation
  1960. * Not implemented in all database drivers, don't use.
  1961. * @param $cursor_offset
  1962. * Not implemented in all database drivers, don't use.
  1963. *
  1964. * @return
  1965. * A result, formatted according to $mode.
  1966. */
  1967. // public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL);
  1968. /**
  1969. * Returns a single field from the next record of a result set.
  1970. *
  1971. * @param $index
  1972. * The numeric index of the field to return. Defaults to the first field.
  1973. *
  1974. * @return
  1975. * A single field from the next record, or FALSE if there is no next record.
  1976. */
  1977. public function fetchField($index = 0);
  1978. /**
  1979. * Fetches the next row and returns it as an object.
  1980. *
  1981. * The object will be of the class specified by DatabaseStatementInterface::setFetchMode()
  1982. * or stdClass if not specified.
  1983. */
  1984. // public function fetchObject();
  1985. /**
  1986. * Fetches the next row and returns it as an associative array.
  1987. *
  1988. * This method corresponds to PDOStatement::fetchObject(), but for associative
  1989. * arrays. For some reason PDOStatement does not have a corresponding array
  1990. * helper method, so one is added.
  1991. *
  1992. * @return
  1993. * An associative array, or FALSE if there is no next row.
  1994. */
  1995. public function fetchAssoc();
  1996. /**
  1997. * Returns an array containing all of the result set rows.
  1998. *
  1999. * @param $mode
  2000. * One of the PDO::FETCH_* constants.
  2001. * @param $column_index
  2002. * If $mode is PDO::FETCH_COLUMN, the index of the column to fetch.
  2003. * @param $constructor_arguments
  2004. * If $mode is PDO::FETCH_CLASS, the arguments to pass to the constructor.
  2005. *
  2006. * @return
  2007. * An array of results.
  2008. */
  2009. // function fetchAll($mode = NULL, $column_index = NULL, array $constructor_arguments);
  2010. /**
  2011. * Returns an entire single column of a result set as an indexed array.
  2012. *
  2013. * Note that this method will run the result set to the end.
  2014. *
  2015. * @param $index
  2016. * The index of the column number to fetch.
  2017. *
  2018. * @return
  2019. * An indexed array, or an empty array if there is no result set.
  2020. */
  2021. public function fetchCol($index = 0);
  2022. /**
  2023. * Returns the entire result set as a single associative array.
  2024. *
  2025. * This method is only useful for two-column result sets. It will return an
  2026. * associative array where the key is one column from the result set and the
  2027. * value is another field. In most cases, the default of the first two columns
  2028. * is appropriate.
  2029. *
  2030. * Note that this method will run the result set to the end.
  2031. *
  2032. * @param $key_index
  2033. * The numeric index of the field to use as the array key.
  2034. * @param $value_index
  2035. * The numeric index of the field to use as the array value.
  2036. *
  2037. * @return
  2038. * An associative array, or an empty array if there is no result set.
  2039. */
  2040. public function fetchAllKeyed($key_index = 0, $value_index = 1);
  2041. /**
  2042. * Returns the result set as an associative array keyed by the given field.
  2043. *
  2044. * If the given key appears multiple times, later records will overwrite
  2045. * earlier ones.
  2046. *
  2047. * @param $key
  2048. * The name of the field on which to index the array.
  2049. * @param $fetch
  2050. * The fetchmode to use. If set to PDO::FETCH_ASSOC, PDO::FETCH_NUM, or
  2051. * PDO::FETCH_BOTH the returned value with be an array of arrays. For any
  2052. * other value it will be an array of objects. By default, the fetch mode
  2053. * set for the query will be used.
  2054. *
  2055. * @return
  2056. * An associative array, or an empty array if there is no result set.
  2057. */
  2058. public function fetchAllAssoc($key, $fetch = NULL);
  2059. }
  2060. /**
  2061. * Default implementation of DatabaseStatementInterface.
  2062. *
  2063. * PDO allows us to extend the PDOStatement class to provide additional
  2064. * functionality beyond that offered by default. We do need extra
  2065. * functionality. By default, this class is not driver-specific. If a given
  2066. * driver needs to set a custom statement class, it may do so in its
  2067. * constructor.
  2068. *
  2069. * @see http://us.php.net/pdostatement
  2070. */
  2071. class DatabaseStatementBase extends PDOStatement implements DatabaseStatementInterface {
  2072. /**
  2073. * Reference to the database connection object for this statement.
  2074. *
  2075. * The name $dbh is inherited from PDOStatement.
  2076. *
  2077. * @var DatabaseConnection
  2078. */
  2079. public $dbh;
  2080. protected function __construct($dbh) {
  2081. $this->dbh = $dbh;
  2082. $this->setFetchMode(PDO::FETCH_OBJ);
  2083. }
  2084. public function execute($args = array(), $options = array()) {
  2085. if (isset($options['fetch'])) {
  2086. if (is_string($options['fetch'])) {
  2087. // Default to an object. Note: db fields will be added to the object
  2088. // before the constructor is run. If you need to assign fields after
  2089. // the constructor is run, see http://drupal.org/node/315092.
  2090. $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
  2091. }
  2092. else {
  2093. $this->setFetchMode($options['fetch']);
  2094. }
  2095. }
  2096. $logger = $this->dbh->getLogger();
  2097. if (!empty($logger)) {
  2098. $query_start = microtime(TRUE);
  2099. }
  2100. $return = parent::execute($args);
  2101. if (!empty($logger)) {
  2102. $query_end = microtime(TRUE);
  2103. $logger->log($this, $args, $query_end - $query_start);
  2104. }
  2105. return $return;
  2106. }
  2107. public function getQueryString() {
  2108. return $this->queryString;
  2109. }
  2110. public function fetchCol($index = 0) {
  2111. return $this->fetchAll(PDO::FETCH_COLUMN, $index);
  2112. }
  2113. public function fetchAllAssoc($key, $fetch = NULL) {
  2114. $return = array();
  2115. if (isset($fetch)) {
  2116. if (is_string($fetch)) {
  2117. $this->setFetchMode(PDO::FETCH_CLASS, $fetch);
  2118. }
  2119. else {
  2120. $this->setFetchMode($fetch);
  2121. }
  2122. }
  2123. foreach ($this as $record) {
  2124. $record_key = is_object($record) ? $record->$key : $record[$key];
  2125. $return[$record_key] = $record;
  2126. }
  2127. return $return;
  2128. }
  2129. public function fetchAllKeyed($key_index = 0, $value_index = 1) {
  2130. $return = array();
  2131. $this->setFetchMode(PDO::FETCH_NUM);
  2132. foreach ($this as $record) {
  2133. $return[$record[$key_index]] = $record[$value_index];
  2134. }
  2135. return $return;
  2136. }
  2137. public function fetchField($index = 0) {
  2138. // Call PDOStatement::fetchColumn to fetch the field.
  2139. return $this->fetchColumn($index);
  2140. }
  2141. public function fetchAssoc() {
  2142. // Call PDOStatement::fetch to fetch the row.
  2143. return $this->fetch(PDO::FETCH_ASSOC);
  2144. }
  2145. }
  2146. /**
  2147. * Empty implementation of a database statement.
  2148. *
  2149. * This class satisfies the requirements of being a database statement/result
  2150. * object, but does not actually contain data. It is useful when developers
  2151. * need to safely return an "empty" result set without connecting to an actual
  2152. * database. Calling code can then treat it the same as if it were an actual
  2153. * result set that happens to contain no records.
  2154. *
  2155. * @see SearchQuery
  2156. */
  2157. class DatabaseStatementEmpty implements Iterator, DatabaseStatementInterface {
  2158. public function execute($args = array(), $options = array()) {
  2159. return FALSE;
  2160. }
  2161. public function getQueryString() {
  2162. return '';
  2163. }
  2164. public function rowCount() {
  2165. return 0;
  2166. }
  2167. public function setFetchMode($mode, $a1 = NULL, $a2 = array()) {
  2168. return;
  2169. }
  2170. public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL) {
  2171. return NULL;
  2172. }
  2173. public function fetchField($index = 0) {
  2174. return NULL;
  2175. }
  2176. public function fetchObject() {
  2177. return NULL;
  2178. }
  2179. public function fetchAssoc() {
  2180. return NULL;
  2181. }
  2182. function fetchAll($mode = NULL, $column_index = NULL, array $constructor_arguments = array()) {
  2183. return array();
  2184. }
  2185. public function fetchCol($index = 0) {
  2186. return array();
  2187. }
  2188. public function fetchAllKeyed($key_index = 0, $value_index = 1) {
  2189. return array();
  2190. }
  2191. public function fetchAllAssoc($key, $fetch = NULL) {
  2192. return array();
  2193. }
  2194. /* Implementations of Iterator. */
  2195. public function current() {
  2196. return NULL;
  2197. }
  2198. public function key() {
  2199. return NULL;
  2200. }
  2201. public function rewind() {
  2202. // Nothing to do: our DatabaseStatement can't be rewound.
  2203. }
  2204. public function next() {
  2205. // Do nothing, since this is an always-empty implementation.
  2206. }
  2207. public function valid() {
  2208. return FALSE;
  2209. }
  2210. }
  2211. /**
  2212. * The following utility functions are simply convenience wrappers.
  2213. *
  2214. * They should never, ever have any database-specific code in them.
  2215. */
  2216. /**
  2217. * Executes an arbitrary query string against the active database.
  2218. *
  2219. * Use this function for SELECT queries if it is just a simple query string.
  2220. * If the caller or other modules need to change the query, use db_select()
  2221. * instead.
  2222. *
  2223. * Do not use this function for INSERT, UPDATE, or DELETE queries. Those should
  2224. * be handled via db_insert(), db_update() and db_delete() respectively.
  2225. *
  2226. * @param $query
  2227. * The prepared statement query to run. Although it will accept both named and
  2228. * unnamed placeholders, named placeholders are strongly preferred as they are
  2229. * more self-documenting.
  2230. * @param $args
  2231. * An array of values to substitute into the query. If the query uses named
  2232. * placeholders, this is an associative array in any order. If the query uses
  2233. * unnamed placeholders (?), this is an indexed array and the order must match
  2234. * the order of placeholders in the query string.
  2235. * @param $options
  2236. * An array of options to control how the query operates.
  2237. *
  2238. * @return DatabaseStatementInterface
  2239. * A prepared statement object, already executed.
  2240. *
  2241. * @see DatabaseConnection::defaultOptions()
  2242. */
  2243. function db_query($query, array $args = array(), array $options = array()) {
  2244. if (empty($options['target'])) {
  2245. $options['target'] = 'default';
  2246. }
  2247. return Database::getConnection($options['target'])->query($query, $args, $options);
  2248. }
  2249. /**
  2250. * Executes a query against the active database, restricted to a range.
  2251. *
  2252. * @param $query
  2253. * The prepared statement query to run. Although it will accept both named and
  2254. * unnamed placeholders, named placeholders are strongly preferred as they are
  2255. * more self-documenting.
  2256. * @param $from
  2257. * The first record from the result set to return.
  2258. * @param $count
  2259. * The number of records to return from the result set.
  2260. * @param $args
  2261. * An array of values to substitute into the query. If the query uses named
  2262. * placeholders, this is an associative array in any order. If the query uses
  2263. * unnamed placeholders (?), this is an indexed array and the order must match
  2264. * the order of placeholders in the query string.
  2265. * @param $options
  2266. * An array of options to control how the query operates.
  2267. *
  2268. * @return DatabaseStatementInterface
  2269. * A prepared statement object, already executed.
  2270. *
  2271. * @see DatabaseConnection::defaultOptions()
  2272. */
  2273. function db_query_range($query, $from, $count, array $args = array(), array $options = array()) {
  2274. if (empty($options['target'])) {
  2275. $options['target'] = 'default';
  2276. }
  2277. return Database::getConnection($options['target'])->queryRange($query, $from, $count, $args, $options);
  2278. }
  2279. /**
  2280. * Executes a SELECT query string and saves the result set to a temporary table.
  2281. *
  2282. * The execution of the query string happens against the active database.
  2283. *
  2284. * @param $query
  2285. * The prepared SELECT statement query to run. Although it will accept both
  2286. * named and unnamed placeholders, named placeholders are strongly preferred
  2287. * as they are more self-documenting.
  2288. * @param $args
  2289. * An array of values to substitute into the query. If the query uses named
  2290. * placeholders, this is an associative array in any order. If the query uses
  2291. * unnamed placeholders (?), this is an indexed array and the order must match
  2292. * the order of placeholders in the query string.
  2293. * @param $options
  2294. * An array of options to control how the query operates.
  2295. *
  2296. * @return
  2297. * The name of the temporary table.
  2298. *
  2299. * @see DatabaseConnection::defaultOptions()
  2300. */
  2301. function db_query_temporary($query, array $args = array(), array $options = array()) {
  2302. if (empty($options['target'])) {
  2303. $options['target'] = 'default';
  2304. }
  2305. return Database::getConnection($options['target'])->queryTemporary($query, $args, $options);
  2306. }
  2307. /**
  2308. * Returns a new InsertQuery object for the active database.
  2309. *
  2310. * @param $table
  2311. * The table into which to insert.
  2312. * @param $options
  2313. * An array of options to control how the query operates.
  2314. *
  2315. * @return InsertQuery
  2316. * A new InsertQuery object for this connection.
  2317. */
  2318. function db_insert($table, array $options = array()) {
  2319. if (empty($options['target']) || $options['target'] == 'slave') {
  2320. $options['target'] = 'default';
  2321. }
  2322. return Database::getConnection($options['target'])->insert($table, $options);
  2323. }
  2324. /**
  2325. * Returns a new MergeQuery object for the active database.
  2326. *
  2327. * @param $table
  2328. * The table into which to merge.
  2329. * @param $options
  2330. * An array of options to control how the query operates.
  2331. *
  2332. * @return MergeQuery
  2333. * A new MergeQuery object for this connection.
  2334. */
  2335. function db_merge($table, array $options = array()) {
  2336. if (empty($options['target']) || $options['target'] == 'slave') {
  2337. $options['target'] = 'default';
  2338. }
  2339. return Database::getConnection($options['target'])->merge($table, $options);
  2340. }
  2341. /**
  2342. * Returns a new UpdateQuery object for the active database.
  2343. *
  2344. * @param $table
  2345. * The table to update.
  2346. * @param $options
  2347. * An array of options to control how the query operates.
  2348. *
  2349. * @return UpdateQuery
  2350. * A new UpdateQuery object for this connection.
  2351. */
  2352. function db_update($table, array $options = array()) {
  2353. if (empty($options['target']) || $options['target'] == 'slave') {
  2354. $options['target'] = 'default';
  2355. }
  2356. return Database::getConnection($options['target'])->update($table, $options);
  2357. }
  2358. /**
  2359. * Returns a new DeleteQuery object for the active database.
  2360. *
  2361. * @param $table
  2362. * The table from which to delete.
  2363. * @param $options
  2364. * An array of options to control how the query operates.
  2365. *
  2366. * @return DeleteQuery
  2367. * A new DeleteQuery object for this connection.
  2368. */
  2369. function db_delete($table, array $options = array()) {
  2370. if (empty($options['target']) || $options['target'] == 'slave') {
  2371. $options['target'] = 'default';
  2372. }
  2373. return Database::getConnection($options['target'])->delete($table, $options);
  2374. }
  2375. /**
  2376. * Returns a new TruncateQuery object for the active database.
  2377. *
  2378. * @param $table
  2379. * The table from which to delete.
  2380. * @param $options
  2381. * An array of options to control how the query operates.
  2382. *
  2383. * @return TruncateQuery
  2384. * A new TruncateQuery object for this connection.
  2385. */
  2386. function db_truncate($table, array $options = array()) {
  2387. if (empty($options['target']) || $options['target'] == 'slave') {
  2388. $options['target'] = 'default';
  2389. }
  2390. return Database::getConnection($options['target'])->truncate($table, $options);
  2391. }
  2392. /**
  2393. * Returns a new SelectQuery object for the active database.
  2394. *
  2395. * @param $table
  2396. * The base table for this query. May be a string or another SelectQuery
  2397. * object. If a query object is passed, it will be used as a subselect.
  2398. * @param $alias
  2399. * The alias for the base table of this query.
  2400. * @param $options
  2401. * An array of options to control how the query operates.
  2402. *
  2403. * @return SelectQuery
  2404. * A new SelectQuery object for this connection.
  2405. */
  2406. function db_select($table, $alias = NULL, array $options = array()) {
  2407. if (empty($options['target'])) {
  2408. $options['target'] = 'default';
  2409. }
  2410. return Database::getConnection($options['target'])->select($table, $alias, $options);
  2411. }
  2412. /**
  2413. * Returns a new transaction object for the active database.
  2414. *
  2415. * @param string $name
  2416. * Optional name of the transaction.
  2417. * @param array $options
  2418. * An array of options to control how the transaction operates:
  2419. * - target: The database target name.
  2420. *
  2421. * @return DatabaseTransaction
  2422. * A new DatabaseTransaction object for this connection.
  2423. */
  2424. function db_transaction($name = NULL, array $options = array()) {
  2425. if (empty($options['target'])) {
  2426. $options['target'] = 'default';
  2427. }
  2428. return Database::getConnection($options['target'])->startTransaction($name);
  2429. }
  2430. /**
  2431. * Sets a new active database.
  2432. *
  2433. * @param $key
  2434. * The key in the $databases array to set as the default database.
  2435. *
  2436. * @return
  2437. * The key of the formerly active database.
  2438. */
  2439. function db_set_active($key = 'default') {
  2440. return Database::setActiveConnection($key);
  2441. }
  2442. /**
  2443. * Restricts a dynamic table name to safe characters.
  2444. *
  2445. * Only keeps alphanumeric and underscores.
  2446. *
  2447. * @param $table
  2448. * The table name to escape.
  2449. *
  2450. * @return
  2451. * The escaped table name as a string.
  2452. */
  2453. function db_escape_table($table) {
  2454. return Database::getConnection()->escapeTable($table);
  2455. }
  2456. /**
  2457. * Restricts a dynamic column or constraint name to safe characters.
  2458. *
  2459. * Only keeps alphanumeric and underscores.
  2460. *
  2461. * @param $field
  2462. * The field name to escape.
  2463. *
  2464. * @return
  2465. * The escaped field name as a string.
  2466. */
  2467. function db_escape_field($field) {
  2468. return Database::getConnection()->escapeField($field);
  2469. }
  2470. /**
  2471. * Escapes characters that work as wildcard characters in a LIKE pattern.
  2472. *
  2473. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  2474. * a backslash. Use this to do a search for a verbatim string without any
  2475. * wildcard behavior.
  2476. *
  2477. * For example, the following does a case-insensitive query for all rows whose
  2478. * name starts with $prefix:
  2479. * @code
  2480. * $result = db_query(
  2481. * 'SELECT * FROM person WHERE name LIKE :pattern',
  2482. * array(':pattern' => db_like($prefix) . '%')
  2483. * );
  2484. * @endcode
  2485. *
  2486. * Backslash is defined as escape character for LIKE patterns in
  2487. * DatabaseCondition::mapConditionOperator().
  2488. *
  2489. * @param $string
  2490. * The string to escape.
  2491. *
  2492. * @return
  2493. * The escaped string.
  2494. */
  2495. function db_like($string) {
  2496. return Database::getConnection()->escapeLike($string);
  2497. }
  2498. /**
  2499. * Retrieves the name of the currently active database driver.
  2500. *
  2501. * @return
  2502. * The name of the currently active database driver.
  2503. */
  2504. function db_driver() {
  2505. return Database::getConnection()->driver();
  2506. }
  2507. /**
  2508. * Closes the active database connection.
  2509. *
  2510. * @param $options
  2511. * An array of options to control which connection is closed. Only the target
  2512. * key has any meaning in this case.
  2513. */
  2514. function db_close(array $options = array()) {
  2515. if (empty($options['target'])) {
  2516. $options['target'] = NULL;
  2517. }
  2518. Database::closeConnection($options['target']);
  2519. }
  2520. /**
  2521. * Retrieves a unique id.
  2522. *
  2523. * Use this function if for some reason you can't use a serial field. Using a
  2524. * serial field is preferred, and InsertQuery::execute() returns the value of
  2525. * the last ID inserted.
  2526. *
  2527. * @param $existing_id
  2528. * After a database import, it might be that the sequences table is behind, so
  2529. * by passing in a minimum ID, it can be assured that we never issue the same
  2530. * ID.
  2531. *
  2532. * @return
  2533. * An integer number larger than any number returned before for this sequence.
  2534. */
  2535. function db_next_id($existing_id = 0) {
  2536. return Database::getConnection()->nextId($existing_id);
  2537. }
  2538. /**
  2539. * Returns a new DatabaseCondition, set to "OR" all conditions together.
  2540. *
  2541. * @return DatabaseCondition
  2542. */
  2543. function db_or() {
  2544. return new DatabaseCondition('OR');
  2545. }
  2546. /**
  2547. * Returns a new DatabaseCondition, set to "AND" all conditions together.
  2548. *
  2549. * @return DatabaseCondition
  2550. */
  2551. function db_and() {
  2552. return new DatabaseCondition('AND');
  2553. }
  2554. /**
  2555. * Returns a new DatabaseCondition, set to "XOR" all conditions together.
  2556. *
  2557. * @return DatabaseCondition
  2558. */
  2559. function db_xor() {
  2560. return new DatabaseCondition('XOR');
  2561. }
  2562. /**
  2563. * Returns a new DatabaseCondition, set to the specified conjunction.
  2564. *
  2565. * Internal API function call. The db_and(), db_or(), and db_xor()
  2566. * functions are preferred.
  2567. *
  2568. * @param $conjunction
  2569. * The conjunction to use for query conditions (AND, OR or XOR).
  2570. * @return DatabaseCondition
  2571. */
  2572. function db_condition($conjunction) {
  2573. return new DatabaseCondition($conjunction);
  2574. }
  2575. /**
  2576. * @} End of "defgroup database".
  2577. */
  2578. /**
  2579. * @addtogroup schemaapi
  2580. * @{
  2581. */
  2582. /**
  2583. * Creates a new table from a Drupal table definition.
  2584. *
  2585. * @param $name
  2586. * The name of the table to create.
  2587. * @param $table
  2588. * A Schema API table definition array.
  2589. */
  2590. function db_create_table($name, $table) {
  2591. return Database::getConnection()->schema()->createTable($name, $table);
  2592. }
  2593. /**
  2594. * Returns an array of field names from an array of key/index column specifiers.
  2595. *
  2596. * This is usually an identity function but if a key/index uses a column prefix
  2597. * specification, this function extracts just the name.
  2598. *
  2599. * @param $fields
  2600. * An array of key/index column specifiers.
  2601. *
  2602. * @return
  2603. * An array of field names.
  2604. */
  2605. function db_field_names($fields) {
  2606. return Database::getConnection()->schema()->fieldNames($fields);
  2607. }
  2608. /**
  2609. * Checks if an index exists in the given table.
  2610. *
  2611. * @param $table
  2612. * The name of the table in drupal (no prefixing).
  2613. * @param $name
  2614. * The name of the index in drupal (no prefixing).
  2615. *
  2616. * @return
  2617. * TRUE if the given index exists, otherwise FALSE.
  2618. */
  2619. function db_index_exists($table, $name) {
  2620. return Database::getConnection()->schema()->indexExists($table, $name);
  2621. }
  2622. /**
  2623. * Checks if a table exists.
  2624. *
  2625. * @param $table
  2626. * The name of the table in drupal (no prefixing).
  2627. *
  2628. * @return
  2629. * TRUE if the given table exists, otherwise FALSE.
  2630. */
  2631. function db_table_exists($table) {
  2632. return Database::getConnection()->schema()->tableExists($table);
  2633. }
  2634. /**
  2635. * Checks if a column exists in the given table.
  2636. *
  2637. * @param $table
  2638. * The name of the table in drupal (no prefixing).
  2639. * @param $field
  2640. * The name of the field.
  2641. *
  2642. * @return
  2643. * TRUE if the given column exists, otherwise FALSE.
  2644. */
  2645. function db_field_exists($table, $field) {
  2646. return Database::getConnection()->schema()->fieldExists($table, $field);
  2647. }
  2648. /**
  2649. * Finds all tables that are like the specified base table name.
  2650. *
  2651. * @param $table_expression
  2652. * An SQL expression, for example "simpletest%" (without the quotes).
  2653. *
  2654. * @return
  2655. * Array, both the keys and the values are the matching tables.
  2656. */
  2657. function db_find_tables($table_expression) {
  2658. return Database::getConnection()->schema()->findTables($table_expression);
  2659. }
  2660. /**
  2661. * Finds all tables that are like the specified base table name. This is a
  2662. * backport of the change made to db_find_tables in Drupal 8 to work with
  2663. * virtual, un-prefixed table names. The original function is retained for
  2664. * Backwards Compatibility.
  2665. * @see https://www.drupal.org/node/2552435
  2666. *
  2667. * @param $table_expression
  2668. * An SQL expression, for example "simpletest%" (without the quotes).
  2669. *
  2670. * @return
  2671. * Array, both the keys and the values are the matching tables.
  2672. */
  2673. function db_find_tables_d8($table_expression) {
  2674. return Database::getConnection()->schema()->findTablesD8($table_expression);
  2675. }
  2676. function _db_create_keys_sql($spec) {
  2677. return Database::getConnection()->schema()->createKeysSql($spec);
  2678. }
  2679. /**
  2680. * Renames a table.
  2681. *
  2682. * @param $table
  2683. * The current name of the table to be renamed.
  2684. * @param $new_name
  2685. * The new name for the table.
  2686. */
  2687. function db_rename_table($table, $new_name) {
  2688. return Database::getConnection()->schema()->renameTable($table, $new_name);
  2689. }
  2690. /**
  2691. * Drops a table.
  2692. *
  2693. * @param $table
  2694. * The table to be dropped.
  2695. */
  2696. function db_drop_table($table) {
  2697. return Database::getConnection()->schema()->dropTable($table);
  2698. }
  2699. /**
  2700. * Adds a new field to a table.
  2701. *
  2702. * @param $table
  2703. * Name of the table to be altered.
  2704. * @param $field
  2705. * Name of the field to be added.
  2706. * @param $spec
  2707. * The field specification array, as taken from a schema definition. The
  2708. * specification may also contain the key 'initial'; the newly-created field
  2709. * will be set to the value of the key in all rows. This is most useful for
  2710. * creating NOT NULL columns with no default value in existing tables.
  2711. * @param $keys_new
  2712. * (optional) Keys and indexes specification to be created on the table along
  2713. * with adding the field. The format is the same as a table specification, but
  2714. * without the 'fields' element. If you are adding a type 'serial' field, you
  2715. * MUST specify at least one key or index including it in this array. See
  2716. * db_change_field() for more explanation why.
  2717. *
  2718. * @see db_change_field()
  2719. */
  2720. function db_add_field($table, $field, $spec, $keys_new = array()) {
  2721. return Database::getConnection()->schema()->addField($table, $field, $spec, $keys_new);
  2722. }
  2723. /**
  2724. * Drops a field.
  2725. *
  2726. * @param $table
  2727. * The table to be altered.
  2728. * @param $field
  2729. * The field to be dropped.
  2730. */
  2731. function db_drop_field($table, $field) {
  2732. return Database::getConnection()->schema()->dropField($table, $field);
  2733. }
  2734. /**
  2735. * Sets the default value for a field.
  2736. *
  2737. * @param $table
  2738. * The table to be altered.
  2739. * @param $field
  2740. * The field to be altered.
  2741. * @param $default
  2742. * Default value to be set. NULL for 'default NULL'.
  2743. */
  2744. function db_field_set_default($table, $field, $default) {
  2745. return Database::getConnection()->schema()->fieldSetDefault($table, $field, $default);
  2746. }
  2747. /**
  2748. * Sets a field to have no default value.
  2749. *
  2750. * @param $table
  2751. * The table to be altered.
  2752. * @param $field
  2753. * The field to be altered.
  2754. */
  2755. function db_field_set_no_default($table, $field) {
  2756. return Database::getConnection()->schema()->fieldSetNoDefault($table, $field);
  2757. }
  2758. /**
  2759. * Adds a primary key to a database table.
  2760. *
  2761. * @param $table
  2762. * Name of the table to be altered.
  2763. * @param $fields
  2764. * Array of fields for the primary key.
  2765. */
  2766. function db_add_primary_key($table, $fields) {
  2767. return Database::getConnection()->schema()->addPrimaryKey($table, $fields);
  2768. }
  2769. /**
  2770. * Drops the primary key of a database table.
  2771. *
  2772. * @param $table
  2773. * Name of the table to be altered.
  2774. */
  2775. function db_drop_primary_key($table) {
  2776. return Database::getConnection()->schema()->dropPrimaryKey($table);
  2777. }
  2778. /**
  2779. * Adds a unique key.
  2780. *
  2781. * @param $table
  2782. * The table to be altered.
  2783. * @param $name
  2784. * The name of the key.
  2785. * @param $fields
  2786. * An array of field names.
  2787. */
  2788. function db_add_unique_key($table, $name, $fields) {
  2789. return Database::getConnection()->schema()->addUniqueKey($table, $name, $fields);
  2790. }
  2791. /**
  2792. * Drops a unique key.
  2793. *
  2794. * @param $table
  2795. * The table to be altered.
  2796. * @param $name
  2797. * The name of the key.
  2798. */
  2799. function db_drop_unique_key($table, $name) {
  2800. return Database::getConnection()->schema()->dropUniqueKey($table, $name);
  2801. }
  2802. /**
  2803. * Adds an index.
  2804. *
  2805. * @param $table
  2806. * The table to be altered.
  2807. * @param $name
  2808. * The name of the index.
  2809. * @param $fields
  2810. * An array of field names.
  2811. */
  2812. function db_add_index($table, $name, $fields) {
  2813. return Database::getConnection()->schema()->addIndex($table, $name, $fields);
  2814. }
  2815. /**
  2816. * Drops an index.
  2817. *
  2818. * @param $table
  2819. * The table to be altered.
  2820. * @param $name
  2821. * The name of the index.
  2822. */
  2823. function db_drop_index($table, $name) {
  2824. return Database::getConnection()->schema()->dropIndex($table, $name);
  2825. }
  2826. /**
  2827. * Changes a field definition.
  2828. *
  2829. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  2830. * recreate all indices and primary keys that are using the changed field.
  2831. *
  2832. * That means that you have to drop all affected keys and indexes with
  2833. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  2834. * To recreate the keys and indices, pass the key definitions as the optional
  2835. * $keys_new argument directly to db_change_field().
  2836. *
  2837. * For example, suppose you have:
  2838. * @code
  2839. * $schema['foo'] = array(
  2840. * 'fields' => array(
  2841. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  2842. * ),
  2843. * 'primary key' => array('bar')
  2844. * );
  2845. * @endcode
  2846. * and you want to change foo.bar to be type serial, leaving it as the primary
  2847. * key. The correct sequence is:
  2848. * @code
  2849. * db_drop_primary_key('foo');
  2850. * db_change_field('foo', 'bar', 'bar',
  2851. * array('type' => 'serial', 'not null' => TRUE),
  2852. * array('primary key' => array('bar')));
  2853. * @endcode
  2854. *
  2855. * The reasons for this are due to the different database engines:
  2856. *
  2857. * On PostgreSQL, changing a field definition involves adding a new field and
  2858. * dropping an old one which causes any indices, primary keys and sequences
  2859. * (from serial-type fields) that use the changed field to be dropped.
  2860. *
  2861. * On MySQL, all type 'serial' fields must be part of at least one key or index
  2862. * as soon as they are created. You cannot use
  2863. * db_add_{primary_key,unique_key,index}() for this purpose because the ALTER
  2864. * TABLE command will fail to add the column without a key or index
  2865. * specification. The solution is to use the optional $keys_new argument to
  2866. * create the key or index at the same time as field.
  2867. *
  2868. * You could use db_add_{primary_key,unique_key,index}() in all cases unless you
  2869. * are converting a field to be type serial. You can use the $keys_new argument
  2870. * in all cases.
  2871. *
  2872. * @param $table
  2873. * Name of the table.
  2874. * @param $field
  2875. * Name of the field to change.
  2876. * @param $field_new
  2877. * New name for the field (set to the same as $field if you don't want to
  2878. * change the name).
  2879. * @param $spec
  2880. * The field specification for the new field.
  2881. * @param $keys_new
  2882. * (optional) Keys and indexes specification to be created on the table along
  2883. * with changing the field. The format is the same as a table specification
  2884. * but without the 'fields' element.
  2885. */
  2886. function db_change_field($table, $field, $field_new, $spec, $keys_new = array()) {
  2887. return Database::getConnection()->schema()->changeField($table, $field, $field_new, $spec, $keys_new);
  2888. }
  2889. /**
  2890. * @} End of "addtogroup schemaapi".
  2891. */
  2892. /**
  2893. * Sets a session variable specifying the lag time for ignoring a slave server.
  2894. */
  2895. function db_ignore_slave() {
  2896. $connection_info = Database::getConnectionInfo();
  2897. // Only set ignore_slave_server if there are slave servers being used, which
  2898. // is assumed if there are more than one.
  2899. if (count($connection_info) > 1) {
  2900. // Five minutes is long enough to allow the slave to break and resume
  2901. // interrupted replication without causing problems on the Drupal site from
  2902. // the old data.
  2903. $duration = variable_get('maximum_replication_lag', 300);
  2904. // Set session variable with amount of time to delay before using slave.
  2905. $_SESSION['ignore_slave_server'] = REQUEST_TIME + $duration;
  2906. }
  2907. }