destinations.db.mysql.inc 18 KB

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