database.inc

You are here

  1. 7 includes/database/mysql/database.inc
  2. 7 includes/database/database.inc
  3. 7 includes/database/pgsql/database.inc
  4. 7 includes/database/sqlite/database.inc
  5. 4.6 includes/database.inc
  6. 4.7 includes/database.inc
  7. 5 includes/database.inc
  8. 6 includes/database.inc
  9. 8 core/includes/database.inc

Core systems for the database layer.

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

Functions

Namesort descending Description
db_add_field Adds a new field to a table.
db_add_index Adds an index.
db_add_primary_key Adds a primary key to a database table.
db_add_unique_key Adds a unique key.
db_and Returns a new DatabaseCondition, set to "AND" all conditions together.
db_change_field Changes a field definition.
db_close Closes the active database connection.
db_condition Returns a new DatabaseCondition, set to the specified conjunction.
db_create_table Creates a new table from a Drupal table definition.
db_delete Returns a new DeleteQuery object for the active database.
db_driver Retrieves the name of the currently active database driver.
db_drop_field Drops a field.
db_drop_index Drops an index.
db_drop_primary_key Drops the primary key of a database table.
db_drop_table Drops a table.
db_drop_unique_key Drops a unique key.
db_escape_field Restricts a dynamic column or constraint name to safe characters.
db_escape_table Restricts a dynamic table name to safe characters.
db_field_exists Checks if a column exists in the given table.
db_field_names Returns an array of field names from an array of key/index column specifiers.
db_field_set_default Sets the default value for a field.
db_field_set_no_default Sets a field to have no default value.
db_find_tables Finds all tables that are like the specified base table name.
db_ignore_slave Sets a session variable specifying the lag time for ignoring a slave server.
db_index_exists Checks if an index exists in the given table.
db_insert Returns a new InsertQuery object for the active database.
db_like Escapes characters that work as wildcard characters in a LIKE pattern.
db_merge Returns a new MergeQuery object for the active database.
db_next_id Retrieves a unique id.
db_or Returns a new DatabaseCondition, set to "OR" all conditions together.
db_query Executes an arbitrary query string against the active database.
db_query_range Executes a query against the active database, restricted to a range.
db_query_temporary Executes a query string and saves the result set to a temporary table.
db_rename_table Renames a table.
db_select Returns a new SelectQuery object for the active database.
db_set_active Sets a new active database.
db_table_exists Checks if a table exists.
db_transaction Returns a new transaction object for the active database.
db_truncate Returns a new TruncateQuery object for the active database.
db_update Returns a new UpdateQuery object for the active database.
db_xor Returns a new DatabaseCondition, set to "XOR" all conditions together.
_db_create_keys_sql

Classes

Namesort descending Description
Database Primary front-controller for the database system.
DatabaseConnection Base Database API class.
DatabaseConnectionNotDefinedException Exception thrown if an undefined database connection is requested.
DatabaseDriverNotSpecifiedException Exception thrown if no driver is specified for a database connection.
DatabaseStatementBase Default implementation of DatabaseStatementInterface.
DatabaseStatementEmpty Empty implementation of a database statement.
DatabaseTransaction A wrapper class for creating and managing database transactions.
DatabaseTransactionCommitFailedException Exception thrown when a commit() function fails.
DatabaseTransactionExplicitCommitNotAllowedException Exception to deny attempts to explicitly manage transactions.
DatabaseTransactionNameNonUniqueException Exception thrown when a savepoint or transaction name occurs twice.
DatabaseTransactionNoActiveException Exception for when popTransaction() is called with no active transaction.
DatabaseTransactionOutOfOrderException Exception thrown when a rollback() resulted in other active transactions being rolled-back.
FieldsOverlapException Exception thrown if an insert query specifies a field twice.
InvalidMergeQueryException Exception thrown for merge queries that do not make semantic sense.
NoFieldsException Exception thrown if an insert query doesn't specify insert or default fields.

Interfaces

Namesort descending Description
DatabaseStatementInterface Represents a prepared statement.

File

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

Comments

Is there any function in Drupal 7 equivalent to mysql_data_seek?

Class 'DatabaseStatementBase' must implement inherited abstract method 'rowCount(...)' in /includes/database/database.inc line 2104 DLTK Problem
Miss one méthode. Drupal Core 7 1.2