rorm_cli/migrate/
config.rs

1use std::fmt::Debug;
2use std::fs::{read_to_string, File};
3use std::io::Write;
4use std::path::Path;
5
6use anyhow::Context;
7use rorm_declaration::config::DatabaseConfig;
8use serde::{Deserialize, Serialize};
9
10/// Outer wrapper for the database configuration file.
11#[derive(Serialize, Deserialize, Debug, Clone)]
12#[serde(rename_all = "PascalCase")]
13pub struct DatabaseConfigFile {
14    pub database: DatabaseConfig,
15}
16
17const EXAMPLE_DATABASE_CONFIG: &str = r#"
18# Example database configuration for each supported database.
19# Uncomment the database you'd like to use.
20
21[Database]
22# -------------------------------
23# Example SQLite configuration
24# -------------------------------
25Driver = "SQLite"
26 
27# Filename / path of the sqlite database 
28Filename = ""
29
30# -------------------------------
31# Example MySQL configuration
32# -------------------------------
33# Driver = "MySQL"
34# Name = "dbname"
35# Host = "127.0.0.1"
36# Port = 3306
37# User = "dbuser"
38# Password = "super-secure-password"
39
40# -------------------------------
41# Example Postgres configuration
42# -------------------------------
43# Driver = "Postgres"
44# Name = "dbname"
45# Host = "127.0.0.1"
46# Port = 5432
47# User = "dbuser"
48# Password = "super-secure-password"
49"#;
50
51#[cfg(test)]
52mod test {
53    use crate::migrate::config::{DatabaseConfigFile, EXAMPLE_DATABASE_CONFIG};
54
55    #[test]
56    fn test_example_database_config() {
57        let db_conf = toml::from_str::<DatabaseConfigFile>(EXAMPLE_DATABASE_CONFIG);
58        assert!(db_conf.is_ok());
59    }
60}
61
62/// Helper method to create a dummy database configuration file
63pub(crate) fn create_db_config(path: &Path) -> anyhow::Result<()> {
64    let fh = File::create(path).with_context(|| format!("Couldn't open {path:?} for writing"))?;
65
66    writeln!(&fh, "{EXAMPLE_DATABASE_CONFIG}").with_context(|| {
67        format!("Couldn't write serialized database configuration to {path:?}",)
68    })?;
69
70    Ok(())
71}
72
73/// Helper method to deserialize an existing database configuration file
74///
75/// - `path`: [`&Path`](Path): Path to the configuration file
76pub fn deserialize_db_conf(path: &Path) -> anyhow::Result<DatabaseConfig> {
77    let db_conf_toml =
78        read_to_string(path).with_context(|| "Couldn't read database configuration file")?;
79
80    let db_conf = toml::from_str::<DatabaseConfigFile>(db_conf_toml.as_str())
81        .with_context(|| "Couldn't deserialize database configuration file")?
82        .database;
83
84    Ok(db_conf)
85}