database.inc 8.2 KB

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