Skip navigation
Help

database.inc

  1. drupal
    1. 6 drupal/includes/database.inc
    2. 7 drupal/includes/database/database.inc
    3. 7 drupal/includes/database/mysql/database.inc
    4. 7 drupal/includes/database/sqlite/database.inc
    5. 7 drupal/includes/database/pgsql/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.

Classes

NameDescription
DatabasePrimary front-controller for the database system.
DatabaseConnectionBase Database API class.
DatabaseConnectionNotDefinedExceptionException thrown if an undefined database connection is requested.
DatabaseDriverNotSpecifiedExceptionException thrown if no driver is specified for a database connection.
DatabaseStatementBaseDefault implementation of DatabaseStatementInterface.
DatabaseStatementEmptyEmpty implementation of a database statement.
DatabaseTransactionA wrapper class for creating and managing database transactions.
DatabaseTransactionCommitFailedExceptionException thrown when a commit() function fails.
DatabaseTransactionExplicitCommitNotAllowedExceptionException to deny attempts to explicitly manage transactions.
DatabaseTransactionNameNonUniqueExceptionException thrown when a savepoint or transaction name occurs twice.
DatabaseTransactionNoActiveExceptionException for when popTransaction() is called with no active transaction.
DatabaseTransactionOutOfOrderExceptionException thrown when a rollback() resulted in other active transactions being rolled-back.
FieldsOverlapExceptionException thrown if an insert query specifies a field twice.
InvalidMergeQueryExceptionException thrown for merge queries that do not make semantic sense.
NoFieldsExceptionException thrown if an insert query doesn't specify insert or default fields.

Interfaces

NameDescription
DatabaseStatementInterfaceA prepared statement.

Functions & methods

NameDescription
db_add_fieldAdds a new field to a table.
db_add_indexAdds an index.
db_add_primary_keyAdds a primary key to a database table.
db_add_unique_keyAdds a unique key.
db_andReturns a new DatabaseCondition, set to "AND" all conditions together.
db_change_fieldChanges a field definition.
db_closeCloses the active database connection.
db_conditionReturns a new DatabaseCondition, set to the specified conjunction.
db_create_tableCreates a new table from a Drupal table definition.
db_deleteReturns a new DeleteQuery object for the active database.
db_driverRetrieves the name of the currently active database driver.
db_drop_fieldDrops a field.
db_drop_indexDrops an index.
db_drop_primary_keyDrops the primary key of a database table.
db_drop_tableDrops a table.
db_drop_unique_keyDrops a unique key.
db_escape_fieldRestricts a dynamic column or constraint name to safe characters.
db_escape_tableRestricts a dynamic table name to safe characters.
db_field_existsChecks if a column exists in the given table.
db_field_namesReturns an array of field names from an array of key/index column specifiers.
db_field_set_defaultSets the default value for a field.
db_field_set_no_defaultSets a field to have no default value.
db_find_tablesFinds all tables that are like the specified base table name.
db_ignore_slaveSets a session variable specifying the lag time for ignoring a slave server.
db_index_existsChecks if an index exists in the given table.
db_insertReturns a new InsertQuery object for the active database.
db_likeEscapes characters that work as wildcard characters in a LIKE pattern.
db_mergeReturns a new MergeQuery object for the active database.
db_next_idRetrieves a unique id.
db_orReturns a new DatabaseCondition, set to "OR" all conditions together.
db_queryExecutes an arbitrary query string against the active database.
db_query_rangeExecutes a query against the active database, restricted to a range.
db_query_temporaryExecutes a query string and saves the result set to a temporary table.
db_rename_tableRenames a table.
db_selectReturns a new SelectQuery object for the active database.
db_set_activeSets a new active database.
db_table_existsChecks if a table exists.
db_transactionReturns a new transaction object for the active database.
db_truncateReturns a new TruncateQuery object for the active database.
db_updateReturns a new UpdateQuery object for the active database.
db_xorReturns a new DatabaseCondition, set to "XOR" all conditions together.
_db_create_keys_sql

File

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