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.

89 lines
2.2 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
  1. use std::borrow::Cow;
  2. use std::error::Error;
  3. use std::fmt;
  4. use command_runner::CommandRunner;
  5. use symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  6. pub struct PostgreSQLDatabase<'a, C: 'a + CommandRunner> {
  7. name: Cow<'a, str>,
  8. seed_file: Cow<'a, str>,
  9. command_runner: &'a C,
  10. }
  11. impl<'a, C: CommandRunner> PostgreSQLDatabase<'a, C> {
  12. pub fn new(name: Cow<'a, str>, seed_file: Cow<'a, str>, command_runner: &'a C) -> Self {
  13. PostgreSQLDatabase {
  14. name,
  15. seed_file,
  16. command_runner,
  17. }
  18. }
  19. fn run_sql(&self, sql: &str) -> Result<String, Box<dyn Error>> {
  20. let b = self.command_runner.get_output(
  21. "su",
  22. &["-", "postgres", "-c", &format!("psql -t -c \"{}\"", sql)],
  23. )?;
  24. Ok(String::from_utf8(b)?)
  25. }
  26. }
  27. impl<'a, C: CommandRunner> fmt::Display for PostgreSQLDatabase<'a, C> {
  28. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  29. write!(f, "PostgreSQL Database {}", self.name)
  30. }
  31. }
  32. impl<'a, C: CommandRunner> Symbol for PostgreSQLDatabase<'a, C> {
  33. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  34. Ok(
  35. self
  36. .run_sql(&format!(
  37. "SELECT datname FROM pg_database WHERE datname LIKE '{}'",
  38. self.name
  39. ))?
  40. .trim()
  41. == self.name,
  42. )
  43. }
  44. fn execute(&self) -> Result<(), Box<dyn Error>> {
  45. self.command_runner.run_successfully(
  46. "su",
  47. &["-", "postgres", "-c", &format!("createuser {}", self.name)],
  48. )?;
  49. self.command_runner.run_successfully(
  50. "su",
  51. &[
  52. "-",
  53. "postgres",
  54. "-c",
  55. &format!("createdb -E UTF8 -T template0 -O {} {0}", self.name),
  56. ],
  57. )?;
  58. self.command_runner.run_successfully(
  59. "su",
  60. &[
  61. "-",
  62. "postgres",
  63. "-c",
  64. &format!("psql '{}' < {}", self.name, self.seed_file),
  65. ],
  66. )
  67. }
  68. fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
  69. Box::new(SymbolAction::new(runner, self))
  70. }
  71. fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
  72. where
  73. Self: 'b,
  74. {
  75. Box::new(OwnedSymbolAction::new(runner, *self))
  76. }
  77. }
  78. #[cfg(test)]
  79. mod test {}