1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::{cli::StopDbCommand, pg::PgEmbedConfig};
use pg_embed::{pg_fetch::PgFetchSettings, postgres::PgEmbed};
use tracing::info;

pub async fn init(command: StopDbCommand) -> anyhow::Result<()> {
    let StopDbCommand {
        name,
        database_dir,
        config,
        verbose,
        ..
    } = command;

    let pg_config =
        PgEmbedConfig::from_file(database_dir.as_ref(), config.as_ref(), &name)?;

    let fetch_settings = PgFetchSettings {
        version: pg_config.postgres_version.clone().into(),
        ..Default::default()
    };

    let mut pg = PgEmbed::new(pg_config.into(), fetch_settings).await?;

    let pg_db_uri = pg.full_db_uri(&name);

    match pg.database_exists(&name).await {
        Ok(exists) => {
            if exists {
                info!("\nStopping database at '{pg_db_uri}'.\n");
                match pg.stop_db().await {
                    Ok(_) => {
                        if verbose {
                            info!("✅ Successfully stopped database at '{pg_db_uri}'.");
                        } else {
                            info!("✅ Successfully stopped database.");
                        }
                    }
                    Err(e) => {
                        anyhow::bail!(
                            "❌ Failed to stop database at '{pg_db_uri}': {e}."
                        );
                    }
                }
            } else {
                anyhow::bail!("❌ Database at '{pg_db_uri}' does not exist.");
            }
        }
        Err(e) => {
            anyhow::bail!("❌ Error determining database's existence: {e}.");
        }
    }

    Ok(())
}