avantis_utils/
db.rs

1//! Db module. include common [DatabaseConfig](crate::db::DatabaseConfig) designed
2//! to be use with Avantis [config](crate::config) module.
3//!
4//! By default, we use Postgres as our database at Avantis.
5
6use std::time::Duration;
7
8use serde::Deserialize;
9
10#[cfg(feature = "db-sqlx")]
11pub mod sqlx;
12
13#[cfg(feature = "db-diesel")]
14pub mod diesel;
15
16/// Standard database config. Designed to be used in config module,
17/// one database per config.
18///
19/// # Example
20///
21/// ```
22/// # use avantis_utils::db::DatabaseConfig;
23/// let config = DatabaseConfig {
24///   host: "localhost".to_string(),
25///   user: "username".to_string(),
26///   password: "REPLACE_ME".to_string(),
27///   db_name: "my_db".to_string(),
28///   max_connections: 30
29/// };
30///
31/// println!("{:?}", config);
32/// // initialize the pool by calling `config.init_pool().await?`
33/// ```
34#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
35pub struct DatabaseConfig {
36    pub host: String,
37    pub user: String,
38    pub password: String,
39    pub db_name: String,
40    pub max_connections: u32,
41}
42
43impl DatabaseConfig {
44    fn connection_timeout(&self) -> Duration {
45        if cfg!(test) {
46            Duration::from_nanos(1)
47        } else {
48            Duration::from_secs(30)
49        }
50    }
51
52    fn postgres_uri(&self) -> String {
53        format!(
54            "postgres://{}:{}@{}/{}",
55            self.user, self.password, self.host, self.db_name
56        )
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use once_cell::sync::Lazy;
63
64    use super::*;
65
66    #[test]
67    fn test_postgres_uri() {
68        assert_eq!(
69            "postgres://username:supersecurepassword@localhost/my_db",
70            CONFIG.postgres_uri(),
71        );
72    }
73
74    static CONFIG: Lazy<DatabaseConfig> = Lazy::new(|| DatabaseConfig {
75        host: "localhost".to_string(),
76        user: "username".to_string(),
77        password: "supersecurepassword".to_string(),
78        db_name: "my_db".to_string(),
79        max_connections: 30,
80    });
81}