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.

52 lines
1.5 KiB

7 years ago
  1. use std::borrow::Cow;
  2. use std::error::Error;
  3. use std::fmt;
  4. use command_runner::CommandRunner;
  5. use symbols::Symbol;
  6. pub struct MariaDBDatabase<'a> {
  7. db_name: Cow<'a, str>,
  8. seed_file: &'a str,
  9. command_runner: &'a CommandRunner
  10. }
  11. impl<'a> MariaDBDatabase<'a> {
  12. pub fn new(db_name: Cow<'a, str>, command_runner: &'a CommandRunner) -> MariaDBDatabase<'a> {
  13. MariaDBDatabase {
  14. db_name: db_name,
  15. seed_file: "/root/seedfile.sql",
  16. command_runner: command_runner
  17. }
  18. }
  19. fn run_sql(&self, sql: &str) -> Result<String, Box<Error>> {
  20. let output = try!(self.command_runner.run_with_args("mariadb", &["--skip-column-names", "-B", "-e", sql]));
  21. if output.status.code() != Some(0) {
  22. return Err(try!(String::from_utf8(output.stderr)).into());
  23. }
  24. Ok(try!(String::from_utf8(output.stdout)))
  25. }
  26. }
  27. impl<'a> fmt::Display for MariaDBDatabase<'a> {
  28. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  29. write!(f, "MariaDB Database {}", self.db_name)
  30. }
  31. }
  32. impl<'a> Symbol for MariaDBDatabase<'a> {
  33. fn target_reached(&self) -> Result<bool, Box<Error>> {
  34. Ok(try!(self.run_sql(&format!("SHOW DATABASES LIKE '{}'", self.db_name))).trim_right() == self.db_name)
  35. }
  36. fn execute(&self) -> Result<(), Box<Error>> {
  37. try!(self.run_sql(&format!("CREATE DATABASE {}", self.db_name)));
  38. try!(self.command_runner.run_with_args("sh", &["-c", &format!("mariadb '{}' < {}", self.db_name, self.seed_file)]));
  39. Ok(())
  40. }
  41. }
  42. #[cfg(test)]
  43. mod test {
  44. }