database.inc

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

Database interface code for MySQL database servers.

File

drupal/includes/database/mysql/database.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Database interface code for MySQL database servers.
  5. */
  6. /**
  7. * @addtogroup database
  8. * @{
  9. */
  10. class DatabaseConnection_mysql extends DatabaseConnection {
  11. /**
  12. * Flag to indicate if the cleanup function in __destruct() should run.
  13. *
  14. * @var boolean
  15. */
  16. protected $needsCleanup = FALSE;
  17. public function __construct(array $connection_options = array()) {
  18. // This driver defaults to transaction support, except if explicitly passed FALSE.
  19. $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
  20. // MySQL never supports transactional DDL.
  21. $this->transactionalDDLSupport = FALSE;
  22. $this->connectionOptions = $connection_options;
  23. // The DSN should use either a socket or a host/port.
  24. if (isset($connection_options['unix_socket'])) {
  25. $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
  26. }
  27. else {
  28. // Default to TCP connection on port 3306.
  29. $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
  30. }
  31. $dsn .= ';dbname=' . $connection_options['database'];
  32. // Allow PDO options to be overridden.
  33. $connection_options += array(
  34. 'pdo' => array(),
  35. );
  36. $connection_options['pdo'] += array(
  37. // So we don't have to mess around with cursors and unbuffered queries by default.
  38. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
  39. // Because MySQL's prepared statements skip the query cache, because it's dumb.
  40. PDO::ATTR_EMULATE_PREPARES => TRUE,
  41. );
  42. parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
  43. // Force MySQL to use the UTF-8 character set. Also set the collation, if a
  44. // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
  45. // for UTF-8.
  46. if (!empty($connection_options['collation'])) {
  47. $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
  48. }
  49. else {
  50. $this->exec('SET NAMES utf8');
  51. }
  52. // Set MySQL init_commands if not already defined. Default Drupal's MySQL
  53. // behavior to conform more closely to SQL standards. This allows Drupal
  54. // to run almost seamlessly on many different kinds of database systems.
  55. // These settings force MySQL to behave the same as postgresql, or sqlite
  56. // in regards to syntax interpretation and invalid data handling. See
  57. // http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
  58. // changed the meaning of TRADITIONAL we need to spell out the modes one by
  59. // one.
  60. $connection_options += array(
  61. 'init_commands' => array(),
  62. );
  63. $connection_options['init_commands'] += array(
  64. 'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
  65. );
  66. // Set connection options.
  67. $this->exec(implode('; ', $connection_options['init_commands']));
  68. }
  69. public function __destruct() {
  70. if ($this->needsCleanup) {
  71. $this->nextIdDelete();
  72. }
  73. }
  74. public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
  75. return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
  76. }
  77. public function queryTemporary($query, array $args = array(), array $options = array()) {
  78. $tablename = $this->generateTemporaryTableName();
  79. $this->query(preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY SELECT', $query), $args, $options);
  80. return $tablename;
  81. }
  82. public function driver() {
  83. return 'mysql';
  84. }
  85. public function databaseType() {
  86. return 'mysql';
  87. }
  88. public function mapConditionOperator($operator) {
  89. // We don't want to override any of the defaults.
  90. return NULL;
  91. }
  92. public function nextId($existing_id = 0) {
  93. $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
  94. // This should only happen after an import or similar event.
  95. if ($existing_id >= $new_id) {
  96. // If we INSERT a value manually into the sequences table, on the next
  97. // INSERT, MySQL will generate a larger value. However, there is no way
  98. // of knowing whether this value already exists in the table. MySQL
  99. // provides an INSERT IGNORE which would work, but that can mask problems
  100. // other than duplicate keys. Instead, we use INSERT ... ON DUPLICATE KEY
  101. // UPDATE in such a way that the UPDATE does not do anything. This way,
  102. // duplicate keys do not generate errors but everything else does.
  103. $this->query('INSERT INTO {sequences} (value) VALUES (:value) ON DUPLICATE KEY UPDATE value = value', array(':value' => $existing_id));
  104. $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
  105. }
  106. $this->needsCleanup = TRUE;
  107. return $new_id;
  108. }
  109. public function nextIdDelete() {
  110. // While we want to clean up the table to keep it up from occupying too
  111. // much storage and memory, we must keep the highest value in the table
  112. // because InnoDB uses an in-memory auto-increment counter as long as the
  113. // server runs. When the server is stopped and restarted, InnoDB
  114. // reinitializes the counter for each table for the first INSERT to the
  115. // table based solely on values from the table so deleting all values would
  116. // be a problem in this case. Also, TRUNCATE resets the auto increment
  117. // counter.
  118. try {
  119. $max_id = $this->query('SELECT MAX(value) FROM {sequences}')->fetchField();
  120. // We know we are using MySQL here, no need for the slower db_delete().
  121. $this->query('DELETE FROM {sequences} WHERE value < :value', array(':value' => $max_id));
  122. }
  123. // During testing, this function is called from shutdown with the
  124. // simpletest prefix stored in $this->connection, and those tables are gone
  125. // by the time shutdown is called so we need to ignore the database
  126. // errors. There is no problem with completely ignoring errors here: if
  127. // these queries fail, the sequence will work just fine, just use a bit
  128. // more database storage and memory.
  129. catch (PDOException $e) {
  130. }
  131. }
  132. /**
  133. * Overridden to work around issues to MySQL not supporting transactional DDL.
  134. */
  135. protected function popCommittableTransactions() {
  136. // Commit all the committable layers.
  137. foreach (array_reverse($this->transactionLayers) as $name => $active) {
  138. // Stop once we found an active transaction.
  139. if ($active) {
  140. break;
  141. }
  142. // If there are no more layers left then we should commit.
  143. unset($this->transactionLayers[$name]);
  144. if (empty($this->transactionLayers)) {
  145. if (!PDO::commit()) {
  146. throw new DatabaseTransactionCommitFailedException();
  147. }
  148. }
  149. else {
  150. // Attempt to release this savepoint in the standard way.
  151. try {
  152. $this->query('RELEASE SAVEPOINT ' . $name);
  153. }
  154. catch (PDOException $e) {
  155. // However, in MySQL (InnoDB), savepoints are automatically committed
  156. // when tables are altered or created (DDL transactions are not
  157. // supported). This can cause exceptions due to trying to release
  158. // savepoints which no longer exist.
  159. //
  160. // To avoid exceptions when no actual error has occurred, we silently
  161. // succeed for MySQL error code 1305 ("SAVEPOINT does not exist").
  162. if ($e->errorInfo[1] == '1305') {
  163. // If one SAVEPOINT was released automatically, then all were.
  164. // Therefore, clean the transaction stack.
  165. $this->transactionLayers = array();
  166. // We also have to explain to PDO that the transaction stack has
  167. // been cleaned-up.
  168. PDO::commit();
  169. }
  170. else {
  171. throw $e;
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. /**
  179. * @} End of "addtogroup database".
  180. */

Classes