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
use crate::{cli::StartDbCommand, pg::PgEmbedConfig};
use pg_embed::{pg_fetch::PgFetchSettings, postgres::PgEmbed};
use tracing::info;

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

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

        let version = pg_config.postgres_version.clone();

        let fetch_settings = PgFetchSettings {
            version: version.clone().into(),
            ..Default::default()
        };
        let pg = PgEmbed::new(pg_config.clone().into(), fetch_settings).await?;
        // Disabling Drop trait behavior as PgEmbed shuts down when going out of scope
        std::mem::ManuallyDrop::new(pg)
    };

    info!("\nStarting PostgreSQL...\n");
    pg.start_db().await?;

    let pg_db_uri = pg.full_db_uri(&name);

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

    Ok(())
}