1use std::fs::File;
2use std::io::Write;
3use std::path::Path;
4use std::process::exit;
5
6use rorm_declaration::config::{DatabaseConfig, DatabaseDriver};
7
8use crate::entry::InitDriver;
9use crate::migrate::config::DatabaseConfigFile;
10
11pub fn init(database_configuration: String, driver: InitDriver, force: bool) -> anyhow::Result<()> {
13 let p = Path::new(&database_configuration);
14 if p.exists() && !force {
15 println!("Database configuration at {} does already exists. Use --force to overwrite the existing file.", &database_configuration);
16 exit(1);
17 }
18
19 match driver {
20 #[cfg(feature = "sqlite")]
21 InitDriver::Sqlite { filename } => {
22 let config_file = DatabaseConfigFile {
23 database: DatabaseConfig {
24 driver: DatabaseDriver::SQLite { filename },
25 last_migration_table_name: None,
26 },
27 };
28
29 let serialized = toml::to_string_pretty(&config_file)?;
30
31 let mut f = File::create(p)?;
32 write!(f, "{}", &serialized)?;
33
34 println!("Configuration was written to {}.", &database_configuration);
35 }
36 #[cfg(feature = "mysql")]
37 InitDriver::Mysql {
38 host,
39 port,
40 user,
41 password,
42 ask_password,
43 name,
44 } => {
45 let pw = if ask_password {
46 rpassword::prompt_password("Enter the password for the database:")?
47 } else {
48 password.unwrap_or_default()
49 };
50
51 let config_file = DatabaseConfigFile {
52 database: DatabaseConfig {
53 driver: DatabaseDriver::MySQL {
54 host,
55 port,
56 user,
57 password: pw,
58 name,
59 },
60 last_migration_table_name: None,
61 },
62 };
63
64 let serialized = toml::to_string_pretty(&config_file)?;
65
66 let mut f = File::create(p)?;
67 write!(f, "{}", &serialized)?;
68
69 println!("Configuration was written to {}.", &database_configuration);
70 }
71 #[cfg(feature = "postgres")]
72 InitDriver::Postgres {
73 host,
74 port,
75 user,
76 password,
77 ask_password,
78 name,
79 } => {
80 let pw = if ask_password {
81 rpassword::prompt_password("Enter the password for the database:")?
82 } else {
83 password.unwrap_or_default()
84 };
85
86 let config_file = DatabaseConfigFile {
87 database: DatabaseConfig {
88 driver: DatabaseDriver::Postgres {
89 host,
90 port,
91 user,
92 password: pw,
93 name,
94 },
95 last_migration_table_name: None,
96 },
97 };
98
99 let serialized = toml::to_string_pretty(&config_file)?;
100
101 let mut f = File::create(p)?;
102 write!(f, "{}", &serialized)?;
103
104 println!("Configuration was written to {}.", &database_configuration);
105 }
106 };
107
108 Ok(())
109}