A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.1 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. use std::error::Error;
  2. use std::fmt;
  3. use std::str::FromStr;
  4. use crate::command_runner::CommandRunner;
  5. use crate::storage::Storage;
  6. use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  7. pub struct DatabaseDump<'a, N: AsRef<str>, C: CommandRunner, S: Storage> {
  8. db_name: N,
  9. storage: S,
  10. command_runner: &'a C,
  11. }
  12. impl<'a, N: AsRef<str>, C: CommandRunner, S: Storage> DatabaseDump<'a, N, C, S> {
  13. pub fn new(db_name: N, storage: S, command_runner: &'a C) -> Self {
  14. DatabaseDump {
  15. db_name,
  16. storage,
  17. command_runner,
  18. }
  19. }
  20. fn run_sql(&self, sql: &str) -> Result<String, Box<dyn Error>> {
  21. let b = self
  22. .command_runner
  23. .get_output("mariadb", args!["--skip-column-names", "-B", "-e", sql])?;
  24. Ok(String::from_utf8(b)?)
  25. }
  26. }
  27. impl<'a, N: AsRef<str>, C: CommandRunner, S: Storage> fmt::Display for DatabaseDump<'a, N, C, S> {
  28. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  29. write!(f, "Dump MariaDB Database {}", self.db_name.as_ref())
  30. }
  31. }
  32. impl<'a, N: AsRef<str>, C: CommandRunner, S: Storage> Symbol for DatabaseDump<'a, N, C, S> {
  33. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  34. let dump_date = self.storage.recent_date()?;
  35. let modified_date = self.run_sql(&format!("select UNIX_TIMESTAMP(MAX(UPDATE_TIME)) from information_schema.tables WHERE table_schema = '{}'", self.db_name.as_ref()))?;
  36. if modified_date.trim_end() == "NULL" {
  37. return Ok(false);
  38. }
  39. Ok(u64::from_str(modified_date.trim_end())? <= dump_date)
  40. }
  41. fn execute(&self) -> Result<(), Box<dyn Error>> {
  42. self.command_runner.run_successfully(
  43. "sh",
  44. args![
  45. "-c",
  46. format!(
  47. "mysqldump '{}' > {}",
  48. self.db_name.as_ref(),
  49. self.storage.write_filename()
  50. ),
  51. ],
  52. )
  53. }
  54. fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
  55. Box::new(SymbolAction::new(runner, self))
  56. }
  57. fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
  58. where
  59. Self: 'b,
  60. {
  61. Box::new(OwnedSymbolAction::new(runner, *self))
  62. }
  63. }
  64. #[cfg(test)]
  65. mod test {}