destinations.db.mysql.inc 17 KB

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