database.inc

  1. 7.x drupal-7.x/includes/database/database.inc
  2. 7.x drupal-7.x/includes/database/mysql/database.inc
  3. 7.x drupal-7.x/includes/database/pgsql/database.inc
  4. 7.x drupal-7.x/includes/database/sqlite/database.inc
  5. 6.x drupal-6.x/includes/database.inc

Core systems for the database layer.

Classes required for basic functioning of the database system should be placed in this file. All utility functions should also be placed in this file only, as they cannot auto-load the way classes can.

File

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