destinations.db.mysql.inc

  1. cis7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  2. cle7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  3. ecd7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  4. elmsmedia7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  5. harmony7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  6. icor7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  7. meedjum_blog7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
  8. mooc7 sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc

Functions to handle the direct to database destination.

Classes

File

sites/all/modules/ulmus/backup_migrate/includes/destinations.db.mysql.inc
View source
  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. $line = trim($line);
  210. // Ignore single line comments.
  211. if (!empty($line) && substr($line, 0, 2) != '--') {
  212. $out .= ' ' . $line;
  213. // If a line ends in ; or */ it is a sql command.
  214. if (substr($out, strlen($out) - 1, 1) == ';' || substr($out, strlen($out) - 2, 2) == '*/') {
  215. return trim($out);
  216. }
  217. }
  218. }
  219. return trim($out);
  220. }
  221. /**
  222. * Get a list of tables in the database.
  223. */
  224. function _get_table_names() {
  225. $out = array();
  226. foreach ($this->_get_tables() as $table) {
  227. $out[$table['name']] = $table['name'];
  228. }
  229. return $out;
  230. }
  231. /**
  232. * Get a list of views in the database.
  233. */
  234. function _get_view_names() {
  235. $out = array();
  236. foreach ($this->_get_views() as $view) {
  237. $out[$view['name']] = $view['name'];
  238. }
  239. return $out;
  240. }
  241. /**
  242. * Lock the list of given tables in the database.
  243. */
  244. function _lock_tables($tables) {
  245. if ($tables) {
  246. $tables_escaped = array();
  247. foreach ($tables as $table) {
  248. $tables_escaped[] = '`'. db_escape_table($table) .'` WRITE';
  249. }
  250. $this->query('LOCK TABLES '. implode(', ', $tables_escaped));
  251. }
  252. }
  253. /**
  254. * Unlock all tables in the database.
  255. */
  256. function _unlock_tables($settings) {
  257. $this->query('UNLOCK TABLES');
  258. }
  259. /**
  260. * Get a list of tables in the db.
  261. */
  262. function _get_tables() {
  263. $out = array();
  264. // get auto_increment values and names of all tables
  265. $tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
  266. foreach ($tables as $table) {
  267. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  268. // See: http://drupal.org/node/1171866
  269. $table = array_change_key_case($table);
  270. if (!empty($table['engine'])) {
  271. $out[$table['name']] = $table;
  272. }
  273. }
  274. return $out;
  275. }
  276. /**
  277. * Get a list of views in the db.
  278. */
  279. function _get_views() {
  280. $out = array();
  281. // get auto_increment values and names of all tables
  282. $tables = $this->query("show table status", array(), array('fetch' => PDO::FETCH_ASSOC));
  283. foreach ($tables as $table) {
  284. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  285. // See: http://drupal.org/node/1171866
  286. $table = array_change_key_case($table);
  287. if (empty($table['engine'])) {
  288. $out[$table['name']] = $table;
  289. }
  290. }
  291. return $out;
  292. }
  293. /**
  294. * Get the sql for the structure of the given table.
  295. */
  296. function _get_table_structure_sql($table) {
  297. $out = "";
  298. $result = $this->query("SHOW CREATE TABLE `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
  299. foreach ($result as $create) {
  300. // Lowercase the keys because between Drupal 7.12 and 7.13/14 the default query behavior was changed.
  301. // See: http://drupal.org/node/1171866
  302. $create = array_change_key_case($create);
  303. $out .= "DROP TABLE IF EXISTS `". $table['name'] ."`;\n";
  304. // Remove newlines and convert " to ` because PDO seems to convert those for some reason.
  305. $out .= strtr($create['create table'], array("\n" => ' ', '"' => '`'));
  306. if ($table['auto_increment']) {
  307. $out .= " AUTO_INCREMENT=". $table['auto_increment'];
  308. }
  309. $out .= ";\n";
  310. }
  311. return $out;
  312. }
  313. /**
  314. * Get the sql for the structure of the given table.
  315. */
  316. function _get_view_create_sql($view) {
  317. $out = "";
  318. // Switch SQL mode to get rid of "CREATE ALGORITHM..." what requires more permissions + troubles with the DEFINER user
  319. $sql_mode = $this->query("SELECT @@SESSION.sql_mode")->fetchField();
  320. $this->query("SET sql_mode = 'ANSI'");
  321. $result = $this->query("SHOW CREATE VIEW `" . $view['name'] . "`", array(), array('fetch' => PDO::FETCH_ASSOC));
  322. $this->query("SET SQL_mode = :mode", array(':mode' => $sql_mode));
  323. foreach ($result as $create) {
  324. $out .= "DROP VIEW IF EXISTS `". $view['name'] ."`;\n";
  325. $out .= "SET sql_mode = 'ANSI';\n";
  326. $out .= strtr($create['Create View'], "\n", " ") . ";\n";
  327. $out .= "SET sql_mode = '$sql_mode';\n";
  328. }
  329. return $out;
  330. }
  331. /**
  332. * Get the sql to insert the data for a given table
  333. */
  334. function _dump_table_data_sql_to_file($file, $table) {
  335. $rows_per_line = variable_get('backup_migrate_data_rows_per_line', 30);
  336. $bytes_per_line = variable_get('backup_migrate_data_bytes_per_line', 2000);
  337. $lines = 0;
  338. $data = $this->query("SELECT * FROM `". $table['name'] ."`", array(), array('fetch' => PDO::FETCH_ASSOC));
  339. $rows = $bytes = 0;
  340. // Escape backslashes, PHP code, special chars
  341. $search = array('\\', "'", "\x00", "\x0a", "\x0d", "\x1a");
  342. $replace = array('\\\\', "''", '\0', '\n', '\r', '\Z');
  343. $line = array();
  344. foreach ($data as $row) {
  345. // DB Escape the values.
  346. $items = array();
  347. foreach ($row as $key => $value) {
  348. $items[] = is_null($value) ? "null" : "'". str_replace($search, $replace, $value) ."'";
  349. }
  350. // If there is a row to be added.
  351. if ($items) {
  352. // Start a new line if we need to.
  353. if ($rows == 0) {
  354. $file->write("INSERT INTO `". $table['name'] ."` VALUES ");
  355. $bytes = $rows = 0;
  356. }
  357. // Otherwise add a comma to end the previous entry.
  358. else {
  359. $file->write(",");
  360. }
  361. // Write the data itself.
  362. $sql = implode(',', $items);
  363. $file->write('('. $sql .')');
  364. $bytes += strlen($sql);
  365. $rows++;
  366. // Finish the last line if we've added enough items
  367. if ($rows >= $rows_per_line || $bytes >= $bytes_per_line) {
  368. $file->write(";\n");
  369. $lines++;
  370. $bytes = $rows = 0;
  371. }
  372. }
  373. }
  374. // Finish any unfinished insert statements.
  375. if ($rows > 0) {
  376. $file->write(";\n");
  377. $lines++;
  378. }
  379. return $lines;
  380. }
  381. /**
  382. * Get the db connection for the specified db.
  383. */
  384. function _get_db_connection() {
  385. if (!$this->connection) {
  386. $this->connection = parent::_get_db_connection();
  387. // Set the sql mode because the default is ANSI,TRADITIONAL which is not aware of collation or storage engine.
  388. $this->connection->exec("SET sql_mode=''");
  389. }
  390. return $this->connection;
  391. }
  392. /**
  393. * Run a db query on this destination's db.
  394. */
  395. function query($query, $args = array(), $options = array()) {
  396. if ($conn = $this->_get_db_connection()) {
  397. return $conn->query($query, $args, $options);
  398. }
  399. }
  400. /**
  401. * The header for the top of the sql dump file. These commands set the connection
  402. * character encoding to help prevent encoding conversion issues.
  403. */
  404. function _get_sql_file_header() {
  405. return "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
  406. /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
  407. /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
  408. /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
  409. /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
  410. /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;
  411. SET NAMES utf8;
  412. ";
  413. }
  414. /**
  415. * The footer of the sql dump file.
  416. */
  417. function _get_sql_file_footer() {
  418. return "
  419. /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
  420. /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
  421. /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
  422. /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
  423. /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
  424. /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
  425. ";
  426. }
  427. }