database.inc

Core systems for the database layer.

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

File

drupal/core/includes/database.inc
View source
  1. <?php
  2. use Drupal\Core\Database\Database;
  3. use Drupal\Core\Database\Query\Condition;
  4. /**
  5. * @file
  6. * Core systems for the database layer.
  7. *
  8. * Classes required for basic functioning of the database system should be
  9. * placed in this file. All utility functions should also be placed in this
  10. * file only, as they cannot auto-load the way classes can.
  11. */
  12. /**
  13. * @defgroup database Database abstraction layer
  14. * @{
  15. * Allow the use of different database servers using the same code base.
  16. *
  17. * Drupal provides a database abstraction layer to provide developers with
  18. * the ability to support multiple database servers easily. The intent of
  19. * this layer is to preserve the syntax and power of SQL as much as possible,
  20. * but also allow developers a way to leverage more complex functionality in
  21. * a unified way. It also provides a structured interface for dynamically
  22. * constructing queries when appropriate, and enforcing security checks and
  23. * similar good practices.
  24. *
  25. * The system is built atop PHP's PDO (PHP Data Objects) database API and
  26. * inherits much of its syntax and semantics.
  27. *
  28. * Most Drupal database SELECT queries are performed by a call to db_query() or
  29. * db_query_range(). Module authors should also consider using the
  30. * Drupal\Core\Database\Query\PagerSelectExtender for queries that return
  31. * results that need to be presented on multiple pages, and the Tablesort
  32. * Extender for generating appropriate queries for sortable tables.
  33. *
  34. * For example, one might wish to return a list of the most recent 10 rows
  35. * authored by a given user. Instead of directly issuing the SQL query
  36. * @code
  37. * SELECT e.id, e.title, e.created FROM example e WHERE e.uid = $uid LIMIT 0, 10;
  38. * @endcode
  39. * one would instead call the Drupal functions:
  40. * @code
  41. * $result = db_query_range('SELECT e.id, e.title, e.created
  42. * FROM {example} e WHERE e.uid = :uid', 0, 10, array(':uid' => $uid));
  43. * foreach ($result as $record) {
  44. * // Perform operations on $record->title, etc. here.
  45. * }
  46. * @endcode
  47. * Curly braces are used around "example" to provide table prefixing via
  48. * DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled
  49. * out into an argument passed to db_query() so that SQL injection attacks
  50. * from user input can be caught and nullified. The LIMIT syntax varies between
  51. * database servers, so that is abstracted into db_query_range() arguments.
  52. * Finally, note the PDO-based ability to iterate over the result set using
  53. * foreach ().
  54. *
  55. * All queries are passed as a prepared statement string. A
  56. * prepared statement is a "template" of a query that omits literal or variable
  57. * values in favor of placeholders. The values to place into those
  58. * placeholders are passed separately, and the database driver handles
  59. * inserting the values into the query in a secure fashion. That means you
  60. * should never quote or string-escape a value to be inserted into the query.
  61. *
  62. * There are two formats for placeholders: named and unnamed. Named placeholders
  63. * are strongly preferred in all cases as they are more flexible and
  64. * self-documenting. Named placeholders should start with a colon ":" and can be
  65. * followed by one or more letters, numbers or underscores.
  66. *
  67. * Named placeholders begin with a colon followed by a unique string. Example:
  68. * @code
  69. * SELECT id, title FROM {example} WHERE uid=:uid;
  70. * @endcode
  71. *
  72. * ":uid" is a placeholder that will be replaced with a literal value when
  73. * the query is executed. A given placeholder label cannot be repeated in a
  74. * given query, even if the value should be the same. When using named
  75. * placeholders, the array of arguments to the query must be an associative
  76. * array where keys are a placeholder label (e.g., :uid) and the value is the
  77. * corresponding value to use. The array may be in any order.
  78. *
  79. * Unnamed placeholders are simply a question mark. Example:
  80. * @code
  81. * SELECT id, title FROM {example} WHERE uid=?;
  82. * @endcode
  83. *
  84. * In this case, the array of arguments must be an indexed array of values to
  85. * use in the exact same order as the placeholders in the query.
  86. *
  87. * Note that placeholders should be a "complete" value. For example, when
  88. * running a LIKE query the SQL wildcard character, %, should be part of the
  89. * value, not the query itself. Thus, the following is incorrect:
  90. * @code
  91. * SELECT id, title FROM {example} WHERE title LIKE :title%;
  92. * @endcode
  93. * It should instead read:
  94. * @code
  95. * SELECT id, title FROM {example} WHERE title LIKE :title;
  96. * @endcode
  97. * and the value for :title should include a % as appropriate. Again, note the
  98. * lack of quotation marks around :title. Because the value is not inserted
  99. * into the query as one big string but as an explicitly separate value, the
  100. * database server knows where the query ends and a value begins. That is
  101. * considerably more secure against SQL injection than trying to remember
  102. * which values need quotation marks and string escaping and which don't.
  103. *
  104. * INSERT, UPDATE, and DELETE queries need special care in order to behave
  105. * consistently across all different databases. Therefore, they use a special
  106. * object-oriented API for defining a query structurally. For example, rather
  107. * than:
  108. * @code
  109. * INSERT INTO {example} (id, uid, path, name) VALUES (1, 2, 'home', 'Home path');
  110. * @endcode
  111. * one would instead write:
  112. * @code
  113. * $fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
  114. * db_insert('node')->fields($fields)->execute();
  115. * @endcode
  116. * This method allows databases that need special data type handling to do so,
  117. * while also allowing optimizations such as multi-insert queries. UPDATE and
  118. * DELETE queries have a similar pattern.
  119. *
  120. * Drupal also supports transactions, including a transparent fallback for
  121. * databases that do not support transactions. To start a new transaction,
  122. * simply call $txn = db_transaction(); in your own code. The transaction will
  123. * remain open for as long as the variable $txn remains in scope. When $txn is
  124. * destroyed, the transaction will be committed. If your transaction is nested
  125. * inside of another then Drupal will track each transaction and only commit
  126. * the outer-most transaction when the last transaction object goes out out of
  127. * scope, that is, all relevant queries completed successfully.
  128. *
  129. * Example:
  130. * @code
  131. * function my_transaction_function() {
  132. * // The transaction opens here.
  133. * $txn = db_transaction();
  134. *
  135. * try {
  136. * $id = db_insert('example')
  137. * ->fields(array(
  138. * 'field1' => 'mystring',
  139. * 'field2' => 5,
  140. * ))
  141. * ->execute();
  142. *
  143. * my_other_function($id);
  144. *
  145. * return $id;
  146. * }
  147. * catch (Exception $e) {
  148. * // Something went wrong somewhere, so roll back now.
  149. * $txn->rollback();
  150. * // Log the exception to watchdog.
  151. * watchdog_exception('type', $e);
  152. * }
  153. *
  154. * // $txn goes out of scope here. Unless the transaction was rolled back, it
  155. * // gets automatically committed here.
  156. * }
  157. *
  158. * function my_other_function($id) {
  159. * // The transaction is still open here.
  160. *
  161. * if ($id % 2 == 0) {
  162. * db_update('example')
  163. * ->condition('id', $id)
  164. * ->fields(array('field2' => 10))
  165. * ->execute();
  166. * }
  167. * }
  168. * @endcode
  169. *
  170. * @see http://drupal.org/developing/api/database
  171. */
  172. /**
  173. * The following utility functions are simply convenience wrappers.
  174. *
  175. * They should never, ever have any database-specific code in them.
  176. */
  177. /**
  178. * Executes an arbitrary query string against the active database.
  179. *
  180. * Use this function for SELECT queries if it is just a simple query string.
  181. * If the caller or other modules need to change the query, use db_select()
  182. * instead.
  183. *
  184. * Do not use this function for INSERT, UPDATE, or DELETE queries. Those should
  185. * be handled via db_insert(), db_update() and db_delete() respectively.
  186. *
  187. * @param $query
  188. * The prepared statement query to run. Although it will accept both named and
  189. * unnamed placeholders, named placeholders are strongly preferred as they are
  190. * more self-documenting.
  191. * @param $args
  192. * An array of values to substitute into the query. If the query uses named
  193. * placeholders, this is an associative array in any order. If the query uses
  194. * unnamed placeholders (?), this is an indexed array and the order must match
  195. * the order of placeholders in the query string.
  196. * @param $options
  197. * An array of options to control how the query operates.
  198. *
  199. * @return DatabaseStatementInterface
  200. * A prepared statement object, already executed.
  201. *
  202. * @see DatabaseConnection::defaultOptions()
  203. */
  204. function db_query($query, array $args = array(), array $options = array()) {
  205. if (empty($options['target'])) {
  206. $options['target'] = 'default';
  207. }
  208. return Database::getConnection($options['target'])->query($query, $args, $options);
  209. }
  210. /**
  211. * Executes a query against the active database, restricted to a range.
  212. *
  213. * @param $query
  214. * The prepared statement query to run. Although it will accept both named and
  215. * unnamed placeholders, named placeholders are strongly preferred as they are
  216. * more self-documenting.
  217. * @param $from
  218. * The first record from the result set to return.
  219. * @param $count
  220. * The number of records to return from the result set.
  221. * @param $args
  222. * An array of values to substitute into the query. If the query uses named
  223. * placeholders, this is an associative array in any order. If the query uses
  224. * unnamed placeholders (?), this is an indexed array and the order must match
  225. * the order of placeholders in the query string.
  226. * @param $options
  227. * An array of options to control how the query operates.
  228. *
  229. * @return DatabaseStatementInterface
  230. * A prepared statement object, already executed.
  231. *
  232. * @see DatabaseConnection::defaultOptions()
  233. */
  234. function db_query_range($query, $from, $count, array $args = array(), array $options = array()) {
  235. if (empty($options['target'])) {
  236. $options['target'] = 'default';
  237. }
  238. return Database::getConnection($options['target'])->queryRange($query, $from, $count, $args, $options);
  239. }
  240. /**
  241. * Executes a query string and saves the result set to a temporary table.
  242. *
  243. * The execution of the query string happens against the active database.
  244. *
  245. * @param $query
  246. * The prepared statement query to run. Although it will accept both named and
  247. * unnamed placeholders, named placeholders are strongly preferred as they are
  248. * more self-documenting.
  249. * @param $args
  250. * An array of values to substitute into the query. If the query uses named
  251. * placeholders, this is an associative array in any order. If the query uses
  252. * unnamed placeholders (?), this is an indexed array and the order must match
  253. * the order of placeholders in the query string.
  254. * @param $options
  255. * An array of options to control how the query operates.
  256. *
  257. * @return
  258. * The name of the temporary table.
  259. *
  260. * @see DatabaseConnection::defaultOptions()
  261. */
  262. function db_query_temporary($query, array $args = array(), array $options = array()) {
  263. if (empty($options['target'])) {
  264. $options['target'] = 'default';
  265. }
  266. return Database::getConnection($options['target'])->queryTemporary($query, $args, $options);
  267. }
  268. /**
  269. * Returns a new InsertQuery object for the active database.
  270. *
  271. * @param $table
  272. * The table into which to insert.
  273. * @param $options
  274. * An array of options to control how the query operates.
  275. *
  276. * @return InsertQuery
  277. * A new InsertQuery object for this connection.
  278. */
  279. function db_insert($table, array $options = array()) {
  280. if (empty($options['target']) || $options['target'] == 'slave') {
  281. $options['target'] = 'default';
  282. }
  283. return Database::getConnection($options['target'])->insert($table, $options);
  284. }
  285. /**
  286. * Returns a new MergeQuery object for the active database.
  287. *
  288. * @param $table
  289. * The table into which to merge.
  290. * @param $options
  291. * An array of options to control how the query operates.
  292. *
  293. * @return MergeQuery
  294. * A new MergeQuery object for this connection.
  295. */
  296. function db_merge($table, array $options = array()) {
  297. if (empty($options['target']) || $options['target'] == 'slave') {
  298. $options['target'] = 'default';
  299. }
  300. return Database::getConnection($options['target'])->merge($table, $options);
  301. }
  302. /**
  303. * Returns a new UpdateQuery object for the active database.
  304. *
  305. * @param $table
  306. * The table to update.
  307. * @param $options
  308. * An array of options to control how the query operates.
  309. *
  310. * @return UpdateQuery
  311. * A new UpdateQuery object for this connection.
  312. */
  313. function db_update($table, array $options = array()) {
  314. if (empty($options['target']) || $options['target'] == 'slave') {
  315. $options['target'] = 'default';
  316. }
  317. return Database::getConnection($options['target'])->update($table, $options);
  318. }
  319. /**
  320. * Returns a new DeleteQuery object for the active database.
  321. *
  322. * @param $table
  323. * The table from which to delete.
  324. * @param $options
  325. * An array of options to control how the query operates.
  326. *
  327. * @return DeleteQuery
  328. * A new DeleteQuery object for this connection.
  329. */
  330. function db_delete($table, array $options = array()) {
  331. if (empty($options['target']) || $options['target'] == 'slave') {
  332. $options['target'] = 'default';
  333. }
  334. return Database::getConnection($options['target'])->delete($table, $options);
  335. }
  336. /**
  337. * Returns a new TruncateQuery object for the active database.
  338. *
  339. * @param $table
  340. * The table from which to delete.
  341. * @param $options
  342. * An array of options to control how the query operates.
  343. *
  344. * @return TruncateQuery
  345. * A new TruncateQuery object for this connection.
  346. */
  347. function db_truncate($table, array $options = array()) {
  348. if (empty($options['target']) || $options['target'] == 'slave') {
  349. $options['target'] = 'default';
  350. }
  351. return Database::getConnection($options['target'])->truncate($table, $options);
  352. }
  353. /**
  354. * Returns a new SelectQuery object for the active database.
  355. *
  356. * @param $table
  357. * The base table for this query. May be a string or another SelectQuery
  358. * object. If a query object is passed, it will be used as a subselect.
  359. * @param $alias
  360. * The alias for the base table of this query.
  361. * @param $options
  362. * An array of options to control how the query operates.
  363. *
  364. * @return SelectQuery
  365. * A new SelectQuery object for this connection.
  366. */
  367. function db_select($table, $alias = NULL, array $options = array()) {
  368. if (empty($options['target'])) {
  369. $options['target'] = 'default';
  370. }
  371. return Database::getConnection($options['target'])->select($table, $alias, $options);
  372. }
  373. /**
  374. * Returns a new transaction object for the active database.
  375. *
  376. * @param string $name
  377. * Optional name of the transaction.
  378. * @param array $options
  379. * An array of options to control how the transaction operates:
  380. * - target: The database target name.
  381. *
  382. * @return DatabaseTransaction
  383. * A new DatabaseTransaction object for this connection.
  384. */
  385. function db_transaction($name = NULL, array $options = array()) {
  386. if (empty($options['target'])) {
  387. $options['target'] = 'default';
  388. }
  389. return Database::getConnection($options['target'])->startTransaction($name);
  390. }
  391. /**
  392. * Sets a new active database.
  393. *
  394. * @param $key
  395. * The key in the $databases array to set as the default database.
  396. *
  397. * @return
  398. * The key of the formerly active database.
  399. */
  400. function db_set_active($key = 'default') {
  401. return Database::setActiveConnection($key);
  402. }
  403. /**
  404. * Restricts a dynamic table name to safe characters.
  405. *
  406. * Only keeps alphanumeric and underscores.
  407. *
  408. * @param $table
  409. * The table name to escape.
  410. *
  411. * @return
  412. * The escaped table name as a string.
  413. */
  414. function db_escape_table($table) {
  415. return Database::getConnection()->escapeTable($table);
  416. }
  417. /**
  418. * Restricts a dynamic column or constraint name to safe characters.
  419. *
  420. * Only keeps alphanumeric and underscores.
  421. *
  422. * @param $field
  423. * The field name to escape.
  424. *
  425. * @return
  426. * The escaped field name as a string.
  427. */
  428. function db_escape_field($field) {
  429. return Database::getConnection()->escapeField($field);
  430. }
  431. /**
  432. * Escapes characters that work as wildcard characters in a LIKE pattern.
  433. *
  434. * The wildcard characters "%" and "_" as well as backslash are prefixed with
  435. * a backslash. Use this to do a search for a verbatim string without any
  436. * wildcard behavior.
  437. *
  438. * You must use a query builder like db_select() in order to use db_like() on
  439. * all supported database systems. Using db_like() with db_query() or
  440. * db_query_range() is not supported.
  441. *
  442. * For example, the following does a case-insensitive query for all rows whose
  443. * name starts with $prefix:
  444. * @code
  445. * $result = db_select('person', 'p')
  446. * ->fields('p')
  447. * ->condition('name', db_like($prefix) . '%', 'LIKE')
  448. * ->execute()
  449. * ->fetchAll();
  450. * @endcode
  451. *
  452. * Backslash is defined as escape character for LIKE patterns in
  453. * DatabaseCondition::mapConditionOperator().
  454. *
  455. * @param $string
  456. * The string to escape.
  457. *
  458. * @return
  459. * The escaped string.
  460. */
  461. function db_like($string) {
  462. return Database::getConnection()->escapeLike($string);
  463. }
  464. /**
  465. * Retrieves the name of the currently active database driver.
  466. *
  467. * @return
  468. * The name of the currently active database driver.
  469. */
  470. function db_driver() {
  471. return Database::getConnection()->driver();
  472. }
  473. /**
  474. * Closes the active database connection.
  475. *
  476. * @param $options
  477. * An array of options to control which connection is closed. Only the target
  478. * key has any meaning in this case.
  479. */
  480. function db_close(array $options = array()) {
  481. if (empty($options['target'])) {
  482. $options['target'] = NULL;
  483. }
  484. Database::closeConnection($options['target']);
  485. }
  486. /**
  487. * Retrieves a unique id.
  488. *
  489. * Use this function if for some reason you can't use a serial field. Using a
  490. * serial field is preferred, and InsertQuery::execute() returns the value of
  491. * the last ID inserted.
  492. *
  493. * @param $existing_id
  494. * After a database import, it might be that the sequences table is behind, so
  495. * by passing in a minimum ID, it can be assured that we never issue the same
  496. * ID.
  497. *
  498. * @return
  499. * An integer number larger than any number returned before for this sequence.
  500. */
  501. function db_next_id($existing_id = 0) {
  502. return Database::getConnection()->nextId($existing_id);
  503. }
  504. /**
  505. * Returns a new DatabaseCondition, set to "OR" all conditions together.
  506. *
  507. * @return Condition
  508. */
  509. function db_or() {
  510. return new Condition('OR');
  511. }
  512. /**
  513. * Returns a new DatabaseCondition, set to "AND" all conditions together.
  514. *
  515. * @return Condition
  516. */
  517. function db_and() {
  518. return new Condition('AND');
  519. }
  520. /**
  521. * Returns a new DatabaseCondition, set to "XOR" all conditions together.
  522. *
  523. * @return Condition
  524. */
  525. function db_xor() {
  526. return new Condition('XOR');
  527. }
  528. /**
  529. * Returns a new DatabaseCondition, set to the specified conjunction.
  530. *
  531. * Internal API function call. The db_and(), db_or(), and db_xor()
  532. * functions are preferred.
  533. *
  534. * @param $conjunction
  535. * The conjunction to use for query conditions (AND, OR or XOR).
  536. * @return Condition
  537. */
  538. function db_condition($conjunction) {
  539. return new Condition($conjunction);
  540. }
  541. /**
  542. * @} End of "defgroup database".
  543. */
  544. /**
  545. * @addtogroup schemaapi
  546. * @{
  547. */
  548. /**
  549. * Creates a new table from a Drupal table definition.
  550. *
  551. * @param $name
  552. * The name of the table to create.
  553. * @param $table
  554. * A Schema API table definition array.
  555. */
  556. function db_create_table($name, $table) {
  557. return Database::getConnection()->schema()->createTable($name, $table);
  558. }
  559. /**
  560. * Returns an array of field names from an array of key/index column specifiers.
  561. *
  562. * This is usually an identity function but if a key/index uses a column prefix
  563. * specification, this function extracts just the name.
  564. *
  565. * @param $fields
  566. * An array of key/index column specifiers.
  567. *
  568. * @return
  569. * An array of field names.
  570. */
  571. function db_field_names($fields) {
  572. return Database::getConnection()->schema()->fieldNames($fields);
  573. }
  574. /**
  575. * Checks if an index exists in the given table.
  576. *
  577. * @param $table
  578. * The name of the table in drupal (no prefixing).
  579. * @param $name
  580. * The name of the index in drupal (no prefixing).
  581. *
  582. * @return
  583. * TRUE if the given index exists, otherwise FALSE.
  584. */
  585. function db_index_exists($table, $name) {
  586. return Database::getConnection()->schema()->indexExists($table, $name);
  587. }
  588. /**
  589. * Checks if a table exists.
  590. *
  591. * @param $table
  592. * The name of the table in drupal (no prefixing).
  593. *
  594. * @return
  595. * TRUE if the given table exists, otherwise FALSE.
  596. */
  597. function db_table_exists($table) {
  598. return Database::getConnection()->schema()->tableExists($table);
  599. }
  600. /**
  601. * Checks if a column exists in the given table.
  602. *
  603. * @param $table
  604. * The name of the table in drupal (no prefixing).
  605. * @param $field
  606. * The name of the field.
  607. *
  608. * @return
  609. * TRUE if the given column exists, otherwise FALSE.
  610. */
  611. function db_field_exists($table, $field) {
  612. return Database::getConnection()->schema()->fieldExists($table, $field);
  613. }
  614. /**
  615. * Finds all tables that are like the specified base table name.
  616. *
  617. * @param $table_expression
  618. * An SQL expression, for example "simpletest%" (without the quotes).
  619. * BEWARE: this is not prefixed, the caller should take care of that.
  620. *
  621. * @return
  622. * Array, both the keys and the values are the matching tables.
  623. */
  624. function db_find_tables($table_expression) {
  625. return Database::getConnection()->schema()->findTables($table_expression);
  626. }
  627. function _db_create_keys_sql($spec) {
  628. return Database::getConnection()->schema()->createKeysSql($spec);
  629. }
  630. /**
  631. * Renames a table.
  632. *
  633. * @param $table
  634. * The current name of the table to be renamed.
  635. * @param $new_name
  636. * The new name for the table.
  637. */
  638. function db_rename_table($table, $new_name) {
  639. return Database::getConnection()->schema()->renameTable($table, $new_name);
  640. }
  641. /**
  642. * Drops a table.
  643. *
  644. * @param $table
  645. * The table to be dropped.
  646. */
  647. function db_drop_table($table) {
  648. return Database::getConnection()->schema()->dropTable($table);
  649. }
  650. /**
  651. * Adds a new field to a table.
  652. *
  653. * @param $table
  654. * Name of the table to be altered.
  655. * @param $field
  656. * Name of the field to be added.
  657. * @param $spec
  658. * The field specification array, as taken from a schema definition. The
  659. * specification may also contain the key 'initial'; the newly-created field
  660. * will be set to the value of the key in all rows. This is most useful for
  661. * creating NOT NULL columns with no default value in existing tables.
  662. * @param $keys_new
  663. * Optional keys and indexes specification to be created on the table along
  664. * with adding the field. The format is the same as a table specification, but
  665. * without the 'fields' element. If you are adding a type 'serial' field, you
  666. * MUST specify at least one key or index including it in this array. See
  667. * db_change_field() for more explanation why.
  668. *
  669. * @see db_change_field()
  670. */
  671. function db_add_field($table, $field, $spec, $keys_new = array()) {
  672. return Database::getConnection()->schema()->addField($table, $field, $spec, $keys_new);
  673. }
  674. /**
  675. * Drops a field.
  676. *
  677. * @param $table
  678. * The table to be altered.
  679. * @param $field
  680. * The field to be dropped.
  681. */
  682. function db_drop_field($table, $field) {
  683. return Database::getConnection()->schema()->dropField($table, $field);
  684. }
  685. /**
  686. * Sets the default value for a field.
  687. *
  688. * @param $table
  689. * The table to be altered.
  690. * @param $field
  691. * The field to be altered.
  692. * @param $default
  693. * Default value to be set. NULL for 'default NULL'.
  694. */
  695. function db_field_set_default($table, $field, $default) {
  696. return Database::getConnection()->schema()->fieldSetDefault($table, $field, $default);
  697. }
  698. /**
  699. * Sets a field to have no default value.
  700. *
  701. * @param $table
  702. * The table to be altered.
  703. * @param $field
  704. * The field to be altered.
  705. */
  706. function db_field_set_no_default($table, $field) {
  707. return Database::getConnection()->schema()->fieldSetNoDefault($table, $field);
  708. }
  709. /**
  710. * Adds a primary key to a database table.
  711. *
  712. * @param $table
  713. * Name of the table to be altered.
  714. * @param $fields
  715. * Array of fields for the primary key.
  716. */
  717. function db_add_primary_key($table, $fields) {
  718. return Database::getConnection()->schema()->addPrimaryKey($table, $fields);
  719. }
  720. /**
  721. * Drops the primary key of a database table.
  722. *
  723. * @param $table
  724. * Name of the table to be altered.
  725. */
  726. function db_drop_primary_key($table) {
  727. return Database::getConnection()->schema()->dropPrimaryKey($table);
  728. }
  729. /**
  730. * Adds a unique key.
  731. *
  732. * @param $table
  733. * The table to be altered.
  734. * @param $name
  735. * The name of the key.
  736. * @param $fields
  737. * An array of field names.
  738. */
  739. function db_add_unique_key($table, $name, $fields) {
  740. return Database::getConnection()->schema()->addUniqueKey($table, $name, $fields);
  741. }
  742. /**
  743. * Drops a unique key.
  744. *
  745. * @param $table
  746. * The table to be altered.
  747. * @param $name
  748. * The name of the key.
  749. */
  750. function db_drop_unique_key($table, $name) {
  751. return Database::getConnection()->schema()->dropUniqueKey($table, $name);
  752. }
  753. /**
  754. * Adds an index.
  755. *
  756. * @param $table
  757. * The table to be altered.
  758. * @param $name
  759. * The name of the index.
  760. * @param $fields
  761. * An array of field names.
  762. */
  763. function db_add_index($table, $name, $fields) {
  764. return Database::getConnection()->schema()->addIndex($table, $name, $fields);
  765. }
  766. /**
  767. * Drops an index.
  768. *
  769. * @param $table
  770. * The table to be altered.
  771. * @param $name
  772. * The name of the index.
  773. */
  774. function db_drop_index($table, $name) {
  775. return Database::getConnection()->schema()->dropIndex($table, $name);
  776. }
  777. /**
  778. * Changes a field definition.
  779. *
  780. * IMPORTANT NOTE: To maintain database portability, you have to explicitly
  781. * recreate all indices and primary keys that are using the changed field.
  782. *
  783. * That means that you have to drop all affected keys and indexes with
  784. * db_drop_{primary_key,unique_key,index}() before calling db_change_field().
  785. * To recreate the keys and indices, pass the key definitions as the optional
  786. * $keys_new argument directly to db_change_field().
  787. *
  788. * For example, suppose you have:
  789. * @code
  790. * $schema['foo'] = array(
  791. * 'fields' => array(
  792. * 'bar' => array('type' => 'int', 'not null' => TRUE)
  793. * ),
  794. * 'primary key' => array('bar')
  795. * );
  796. * @endcode
  797. * and you want to change foo.bar to be type serial, leaving it as the primary
  798. * key. The correct sequence is:
  799. * @code
  800. * db_drop_primary_key('foo');
  801. * db_change_field('foo', 'bar', 'bar',
  802. * array('type' => 'serial', 'not null' => TRUE),
  803. * array('primary key' => array('bar')));
  804. * @endcode
  805. *
  806. * The reasons for this are due to the different database engines:
  807. *
  808. * On PostgreSQL, changing a field definition involves adding a new field and
  809. * dropping an old one which causes any indices, primary keys and sequences
  810. * (from serial-type fields) that use the changed field to be dropped.
  811. *
  812. * On MySQL, all type 'serial' fields must be part of at least one key or index
  813. * as soon as they are created. You cannot use
  814. * db_add_{primary_key,unique_key,index}() for this purpose because the ALTER
  815. * TABLE command will fail to add the column without a key or index
  816. * specification. The solution is to use the optional $keys_new argument to
  817. * create the key or index at the same time as field.
  818. *
  819. * You could use db_add_{primary_key,unique_key,index}() in all cases unless you
  820. * are converting a field to be type serial. You can use the $keys_new argument
  821. * in all cases.
  822. *
  823. * @param $table
  824. * Name of the table.
  825. * @param $field
  826. * Name of the field to change.
  827. * @param $field_new
  828. * New name for the field (set to the same as $field if you don't want to
  829. * change the name).
  830. * @param $spec
  831. * The field specification for the new field.
  832. * @param $keys_new
  833. * Optional keys and indexes specification to be created on the table along
  834. * with changing the field. The format is the same as a table specification
  835. * but without the 'fields' element.
  836. */
  837. function db_change_field($table, $field, $field_new, $spec, $keys_new = array()) {
  838. return Database::getConnection()->schema()->changeField($table, $field, $field_new, $spec, $keys_new);
  839. }
  840. /**
  841. * @} End of "addtogroup schemaapi".
  842. */
  843. /**
  844. * Sets a session variable specifying the lag time for ignoring a slave server.
  845. */
  846. function db_ignore_slave() {
  847. $connection_info = Database::getConnectionInfo();
  848. // Only set ignore_slave_server if there are slave servers being used, which
  849. // is assumed if there are more than one.
  850. if (count($connection_info) > 1) {
  851. // Five minutes is long enough to allow the slave to break and resume
  852. // interrupted replication without causing problems on the Drupal site from
  853. // the old data.
  854. $duration = settings()->get('maximum_replication_lag', 300);
  855. // Set session variable with amount of time to delay before using slave.
  856. $_SESSION['ignore_slave_server'] = REQUEST_TIME + $duration;
  857. }
  858. }

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