database.inc 8.5 KB

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