use std::path::Path;
use crate::command_executor::{AsyncCommand, AsyncCommandExecutor};
use crate::pg_enums::{PgAuthMethod, PgProcessType, PgServerStatus};
use crate::pg_errors::Error;
use crate::pg_errors::Result;
pub struct PgCommand {}
impl PgCommand {
pub fn init_db_executor(
init_db_exe: &Path,
database_dir: &Path,
pw_file_path: &Path,
user: &str,
auth_method: &PgAuthMethod,
) -> Result<AsyncCommandExecutor<PgServerStatus, Error, PgProcessType>> {
let init_db_executable = init_db_exe.as_os_str();
let pw_file_str = pw_file_path
.to_str()
.ok_or(Error::InvalidPgUrl)?;
let password_file_arg = format!("--pwfile={}", pw_file_str);
let auth_host = match auth_method {
PgAuthMethod::Plain => "password",
PgAuthMethod::MD5 => "md5",
PgAuthMethod::ScramSha256 => "scram-sha-256",
};
let db_dir_str = database_dir.to_str().ok_or(Error::InvalidPgUrl)?;
let args = [
"-A",
auth_host,
"-U",
user,
"-E=UTF8",
"-D",
db_dir_str,
&password_file_arg,
];
AsyncCommandExecutor::<PgServerStatus, Error, PgProcessType>::new(
init_db_executable,
args,
PgProcessType::InitDb,
)
}
pub fn start_db_executor(
pg_ctl_exe: &Path,
database_dir: &Path,
port: &u16,
) -> Result<AsyncCommandExecutor<PgServerStatus, Error, PgProcessType>> {
let pg_ctl_executable = pg_ctl_exe.as_os_str();
let port_arg = format!("-F -p {}", port);
let db_dir_str = database_dir.to_str().ok_or(Error::InvalidPgUrl)?;
let args = ["-o", &port_arg, "start", "-w", "-D", db_dir_str];
AsyncCommandExecutor::<PgServerStatus, Error, PgProcessType>::new(
pg_ctl_executable,
args,
PgProcessType::StartDb,
)
}
pub fn stop_db_executor(
pg_ctl_exe: &Path,
database_dir: &Path,
) -> Result<AsyncCommandExecutor<PgServerStatus, Error, PgProcessType>> {
let pg_ctl_executable = pg_ctl_exe.as_os_str();
let db_dir_str = database_dir.to_str().ok_or(Error::InvalidPgUrl)?;
let args = ["stop", "-w", "-D", db_dir_str];
AsyncCommandExecutor::<PgServerStatus, Error, PgProcessType>::new(
pg_ctl_executable,
args,
PgProcessType::StopDb,
)
}
}