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.

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