destinations.db.mysql.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. backup_migrate_include('destinations.db');
  3. /**
  4. * @file
  5. * Functions to handle the direct to database destination.
  6. */
  7. /**
  8. * A destination type for saving to a database server.
  9. *
  10. * @ingroup backup_migrate_destinations
  11. */
  12. class backup_migrate_destination_db_mysql extends backup_migrate_destination_db {
  13. function type_name() {
  14. return t("MySQL Database");
  15. }
  16. /**
  17. * Return a list of backup filetypes.
  18. */
  19. function file_types() {
  20. return array(
  21. "sql" => array(
  22. "extension" => "sql",
  23. "filemime" => "text/x-sql",
  24. "backup" => TRUE,
  25. "restore" => TRUE,
  26. ),
  27. "mysql" => array(
  28. "extension" => "mysql",
  29. "filemime" => "text/x-sql",
  30. "backup" => TRUE,
  31. "restore" => TRUE,
  32. ),
  33. );
  34. }
  35. /**
  36. * Declare any mysql databases defined in the settings.php file as a possible destination.
  37. */
  38. function destinations() {
  39. $out = array();
  40. global $databases;
  41. foreach ((array)$databases as $db_key => $target) {
  42. foreach ((array)$target as $tgt_key => $info) {
  43. // Only mysql/mysqli supported by this destination.
  44. $key = $db_key . ':' . $tgt_key;
  45. if ($info['driver'] === 'mysql') {
  46. $url = $info['driver'] . '://' . $info['username'] . ':' . $info['password'] . '@' . $info['host'] . (isset($info['port']) ? ':' . $info['port'] : '') . '/' . $info['database'];
  47. if ($destination = backup_migrate_create_destination('mysql', array('url' => $url))) {
  48. // Treat the default database differently because it is probably the only one available.
  49. if ($key == 'default:default') {
  50. $destination->set_id('db');
  51. $destination->set_name(t('Default Database'));
  52. // Dissalow backing up to the default database because that's confusing and potentially dangerous.
  53. $destination->remove_op('scheduled backup');
  54. $destination->remove_op('manual backup');
  55. }
  56. else {
  57. $destination->set_id('db:'. $key);
  58. $destination->set_name($key .": ". $destination->get_display_location());
  59. }
  60. $out[$destination->get_id()] = $destination;
  61. }
  62. }
  63. }
  64. }
  65. return $out;
  66. }
  67. /**
  68. * Get the file type for to backup this destination to.
  69. */
  70. function get_file_type_id() {
  71. return 'mysql';
  72. }
  73. /**
  74. * Get the form for the backup settings for this destination.
  75. */
  76. function backup_settings_form($settings) {
  77. $form = parent::backup_settings_form($settings);
  78. $form['use_mysqldump'] = array(
  79. "#type" => "checkbox",
  80. "#title" => t("Use mysqldump command"),
  81. "#default_value" => !empty($settings['use_mysqldump']),
  82. "#description" => t("Use the mysqldump command line tool if available. This can be faster for large databases but will not work on all servers. Also exporting SQL views is not really solid with this option. EXPERIMENTAL"),
  83. );
  84. return $form;
  85. }
  86. /**
  87. * Backup the databases to a file.
  88. *
  89. * Returns a list of sql commands, one command per line.
  90. * That makes it easier to import without loading the whole file into memory.
  91. * The files are a little harder to read, but human-readability is not a priority
  92. */
  93. function _backup_db_to_file($file, $settings) {
  94. if (!empty($settings->filters['use_mysqldump']) && $this->_backup_db_to_file_mysqldump($file, $settings)) {
  95. return TRUE;
  96. }
  97. $lines = 0;
  98. $exclude = !empty($settings->filters['exclude_tables']) ? $settings->filters['exclude_tables'] : array();
  99. $nodata = !empty($settings->filters['nodata_tables']) ? $settings->filters['nodata_tables'] : array();
  100. if ($file->open(TRUE)) {
  101. $file->write($this->_get_sql_file_header());
  102. $alltables = $this->_get_tables();
  103. $allviews = $this->_get_views();
  104. foreach ($alltables as $table) {
  105. if (_backup_migrate_check_timeout()) {
  106. return FALSE;
  107. }
  108. if ($table['name'] && !isset($exclude[$table['name']])) {
  109. $file->write($this->_get_table_structure_sql($table));
  110. $lines++;
  111. if (!in_array($table['name'], $nodata)) {
  112. $lines += $this->_dump_table_data_sql_to_file($file, $table);
  113. }
  114. }
  115. }
  116. foreach ($allviews as $view) {
  117. if (_backup_migrate_check_timeout()) {
  118. return FALSE;
  119. }
  120. if ($view['name'] && !isset($exclude[$view['name']])) {
  121. $file->write($this->_get_view_create_sql($view));
  122. }
  123. }
  124. $file->write($this->_get_sql_file_footer());
  125. $file->close();
  126. return $lines;
  127. }
  128. else {
  129. return FALSE;
  130. }
  131. }
  132. /**
  133. * Backup the databases to a file using the mysqldump command.
  134. */
  135. function _backup_db_to_file_mysqldump($file, $settings) {
  136. $success = FALSE;
  137. $nodata_tables = array();
  138. $alltables = $this->_get_tables();
  139. $command = 'mysqldump --result-file=%file --opt -Q --host=%host --port=%port --user=%user --password=%pass %db';
  140. $args = array(
  141. '%file' => $file->filepath(),
  142. '%host' => $this->dest_url['host'],
  143. '%port' => !empty($this->dest_url['port']) ? $this->dest_url['port'] : '3306',
  144. '%user' => $this->dest_url['user'],
  145. '%pass' => $this->dest_url['pass'],
  146. '%db' => $this->dest_url['path'],
  147. );
  148. // Ignore the excluded and no-data tables.
  149. $db = $this->dest_url['path'];
  150. if (!empty($settings->filters['exclude_tables'])) {
  151. foreach ((array)$settings->filters['exclude_tables'] as $table) {
  152. if (isset($alltables[$table])) {
  153. $command .= ' --ignore-table='. $db .'.'. $table;
  154. }
  155. }
  156. }
  157. if (!empty($settings->filters['nodata_tables'])) {
  158. foreach ((array)$settings->filters['nodata_tables'] as $table) {
  159. if (isset($alltables[$table])) {
  160. $nodata_tables[] = $table;
  161. $command .= ' --ignore-table='. $db .'.'. $table;
  162. }
  163. }
  164. }
  165. $success = backup_migrate_exec($command, $args);
  166. // Get the nodata tables.
  167. if ($success && !empty($nodata_tables)) {
  168. $tables = implode(' ', array_unique($nodata_tables));
  169. $command = "mysqldump --no-data --opt -Q --host=%host --port=%port --user=%user --password=%pass %db $tables >> %file";
  170. $success = backup_migrate_exec($command, $args);
  171. }
  172. return $success;
  173. }
  174. /**
  175. * Backup the databases to a file.
  176. */
  177. function _restore_db_from_file($file, $settings) {
  178. $num = 0;
  179. if ($file->open() && $conn = $this->_get_db_connection()) {
  180. // Read one line at a time and run the query.
  181. while ($line = $this->_read_sql_command_from_file($file)) {
  182. if (_backup_migrate_check_timeout()) {
  183. return FALSE;
  184. }
  185. if ($line) {
  186. // Prepeare and exexute the statement instead of the api function to avoid substitution of '{' etc.
  187. $stmt = $conn->prepare($line);
  188. $stmt->execute();
  189. $num++;
  190. }
  191. }
  192. // Close the file with fclose/gzclose.
  193. $file->close();
  194. }
  195. else {
  196. drupal_set_message(t("Unable to open file %file to restore database", array("%file" => $file->filepath())), 'error');
  197. $num = FALSE;
  198. }
  199. return $num;
  200. }
  201. /**
  202. * Read a multiline sql command from a file.
  203. *
  204. * Supports the formatting created by mysqldump, but won't handle multiline comments.
  205. */
  206. function _read_sql_command_from_file($file) {
  207. $out = '';
  208. while ($line = $file->read()) {
  209. $first2 = substr($line, 0, 2);
  210. $first3 = substr($line, 0, 2);
  211. // Ignore single line comments. This function doesn't support multiline comments or inline comments.
  212. if ($first2 != '--' && ($first2 != '/*' || $first3 == '/*!')) {
  213. $out .= ' ' . trim($line);
  214. // If a line ends in ; or */ it is a sql command.
  215. if (substr($out, strlen($out) - 1, 1) == ';') {
  216. return trim($out);
  217. }
  218. }
  219. }
  220. return trim($out);
  221. }
  222. /**
  223. * Get a list of tables in the database.
  224. */
  225. function _get_table_names() {
  226. $out = array();
  227. foreach ($this->_get_tables() as $table) {
  228. $out[$table['name']] = $table['name'];
  229. }
  230. return $out;
  231. }
  232. /**
  233. * Get a list of views in the database.
  234. */
  235. function _get_view_names() {
  236. $out = array();
  237. foreach ($this->_get_views() as $view) {
  238. $out[$view['name']] = $view['name'];
  239. }
  240. return $out;
  241. }
  242. /**
  243. * Lock the list of given tables in the database.
  244. */
  245. function _lock_tables($tables) {
  246. if ($tables) {
  247. $tables_escaped = array();
  248. foreach ($tables as $table) {
  249. $tables_escaped[] = '`'. db_escape_table($table) .'` WRITE';
  250. }
  251. $this->query('LOCK TABLES '. implode(', ', $tables_escaped));
  252. }
  253. }
  254. /**
  255. * Unlock all tables in the database.
  256. */
  257. function _unlock_tables($settings) {
  258. $this->query('UNLOCK TABLES');
  259. }
  260. /**
  261. * Get a list of tables in the db.
  262. */
  263. function _get_tables() {
  264. $out = array();
  265. // get auto_increment values and names of all tables
  266. $tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
  267. foreach ($tables as $table) {
  268. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  269. // See: http://drupal.org/node/1171866
  270. $table = array_change_key_case($table);
  271. if (!empty($table['engine'])) {
  272. $out[$table['name']] = $table;
  273. }
  274. }
  275. return $out;
  276. }
  277. /**
  278. * Get a list of views in the db.
  279. */
  280. function _get_views() {
  281. $out = array();
  282. // get auto_increment values and names of all tables
  283. $tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
  284. foreach ($tables as $table) {
  285. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  286. // See: http://drupal.org/node/1171866
  287. $table = array_change_key_case($table);
  288. if (empty($table['engine'])) {
  289. $out[$table['name']] = $table;
  290. }
  291. }
  292. return $out;
  293. }
  294. /**
  295. * Get the sql for the structure of the given table.
  296. */
  297. function _get_table_structure_sql($table) {
  298. $out = "";
  299. $result = $this->query("SHOW CREATE TABLE `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
  300. foreach ($result as $create) {
  301. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  302. // See: http://drupal.org/node/1171866
  303. $create = array_change_key_case($create);
  304. $out .= "DROP TABLE IF EXISTS `". $table['name'] ."`;\n";
  305. // Remove newlines and convert " to ` because PDO seems to convert those for some reason.
  306. $out .= strtr($create['create table'], array("\n" => ' ', '"' => '`'));
  307. if ($table['auto_increment']) {
  308. $out .= " AUTO_INCREMENT=". $table['auto_increment'];
  309. }
  310. $out .= ";\n";
  311. }
  312. return $out;
  313. }
  314. /**
  315. * Get the sql for the structure of the given table.
  316. */
  317. function _get_view_create_sql($view) {
  318. $out = "";
  319. // Switch SQL mode to get rid of "CREATE ALGORITHM..." what requires more permissions + troubles with the DEFINER user
  320. $sql_mode = $this->query("SELECT @@SESSION.sql_mode")->fetchField();
  321. $this->query("SET sql_mode = 'ANSI'");
  322. $result = $this->query("SHOW CREATE VIEW `" . $view['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
  323. $this->query("SET SQL_mode = :mode", array(':mode' => $sql_mode));
  324. foreach ($result as $create) {
  325. $out .= "DROP VIEW IF EXISTS `". $view['name'] ."`;\n";
  326. $out .= "SET sql_mode = 'ANSI';\n";
  327. $out .= strtr($create['Create View'], "\n", " ") . ";\n";
  328. $out .= "SET sql_mode = '$sql_mode';\n";
  329. }
  330. return $out;
  331. }
  332. /**
  333. * Get the sql to insert the data for a given table
  334. */
  335. function _dump_table_data_sql_to_file($file, $table) {
  336. $rows_per_line = variable_get('backup_migrate_data_rows_per_line', 30);
  337. $bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', 2000);
  338. $lines = 0;
  339. $data = $this->query("SELECT * FROM `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
  340. $rows = $bytes = 0;
  341. // Escape backslashes, PHP code, special chars
  342. $search = array('\\', "'", "\x00", "\x0a", "\x0d", "\x1a");
  343. $replace = array('\\\\', "''", '\0', '\n', '\r', '\Z');
  344. $line = array();
  345. foreach ($data as $row) {
  346. // DB Escape the values.
  347. $items = array();
  348. foreach ($row as $key => $value) {
  349. $items[] = is_null($value) ? "null" : "'". str_replace($search, $replace, $value) ."'";
  350. }
  351. // If there is a row to be added.
  352. if ($items) {
  353. // Start a new line if we need to.
  354. if ($rows == 0) {
  355. $file->write("INSERT INTO `". $table['name'] ."` VALUES ");
  356. $bytes = $rows = 0;
  357. }
  358. // Otherwise add a comma to end the previous entry.
  359. else {
  360. $file->write(",");
  361. }
  362. // Write the data itself.
  363. $sql = implode(',', $items);
  364. $file->write('('. $sql .')');
  365. $bytes += strlen($sql);
  366. $rows++;
  367. // Finish the last line if we've added enough items
  368. if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
  369. $file->write(";\n");
  370. $lines++;
  371. $bytes = $rows = 0;
  372. }
  373. }
  374. }
  375. // Finish any unfinished insert statements.
  376. if ($rows > 0) {
  377. $file->write(";\n");
  378. $lines++;
  379. }
  380. return $lines;
  381. }
  382. /**
  383. * Get the db connection for the specified db.
  384. */
  385. function _get_db_connection() {
  386. if (!$this->connection) {
  387. $this->connection = parent::_get_db_connection();
  388. // Set the sql mode because the default is ANSI,TRADITIONAL which is not aware of collation or storage engine.
  389. $this->connection->exec("SET sql_mode=''");
  390. }
  391. return $this->connection;
  392. }
  393. /**
  394. * Run a db query on this destination's db.
  395. */
  396. function query($query, $args = array(), $options = array()) {
  397. if ($conn = $this->_get_db_connection()) {
  398. return $conn->query($query, $args, $options);
  399. }
  400. }
  401. /**
  402. * The header for the top of the sql dump file. These commands set the connection
  403. * character encoding to help prevent encoding conversion issues.
  404. */
  405. function _get_sql_file_header() {
  406. return "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
  407. /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
  408. /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
  409. /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
  410. /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
  411. /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
  412. SET NAMES utf8;
  413. ";
  414. }
  415. /**
  416. * The footer of the sql dump file.
  417. */
  418. function _get_sql_file_footer() {
  419. return "
  420. /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
  421. /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
  422. /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
  423. /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
  424. /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
  425. /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
  426. ";
  427. }
  428. }