database.inc 9.9 KB

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