Skip to main content

rorm_cli/init/
mod.rs

1use std::fs;
2use std::path::Path;
3
4use rorm_declaration::config::{DatabaseConfig, DatabaseDriver};
5use tracing::{error, info};
6
7use crate::cli::InitDriver;
8use crate::migrate::config::DatabaseConfigFile;
9
10/// Create the database configuration file
11pub fn init(database_configuration: String, driver: InitDriver, force: bool) -> anyhow::Result<()> {
12    let p = Path::new(&database_configuration);
13    if p.exists() && !force {
14        error!("Database configuration at {} does already exists. Use --force to overwrite the existing file.", &database_configuration);
15        return Ok(());
16    }
17
18    match driver {
19        #[cfg(feature = "sqlite")]
20        InitDriver::Sqlite { filename } => {
21            let config_file = DatabaseConfigFile {
22                database: DatabaseConfig {
23                    driver: DatabaseDriver::SQLite { filename },
24                    last_migration_table_name: None,
25                },
26            };
27
28            let serialized = toml::to_string_pretty(&config_file)?;
29
30            fs::write(p, serialized)?;
31        }
32        #[cfg(feature = "postgres")]
33        InitDriver::Postgres {
34            host,
35            port,
36            user,
37            password,
38            ask_password,
39            name,
40        } => {
41            let pw = if ask_password {
42                rpassword::prompt_password("Enter the password for the database:")?
43            } else {
44                password.unwrap_or_default()
45            };
46
47            let config_file = DatabaseConfigFile {
48                database: DatabaseConfig {
49                    driver: DatabaseDriver::Postgres {
50                        host,
51                        port,
52                        user,
53                        password: pw,
54                        name,
55                    },
56                    last_migration_table_name: None,
57                },
58            };
59
60            let serialized = toml::to_string_pretty(&config_file)?;
61
62            fs::write(p, serialized)?;
63        }
64    }
65
66    info!("Configuration was written to {}.", &database_configuration);
67
68    Ok(())
69}