Skip navigation
Help

database.inc

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

Database interface code for MySQL database servers.

Classes

NameDescription
DatabaseConnection_mysql

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