pub struct DbConfig {
pub database_url: String,
pub min_connections: u32,
pub max_connections: u32,
pub acquire_timeout: Duration,
pub idle_timeout: Duration,
pub test_before_acquire: bool,
}Expand description
Settings used to establish a connection with a database, regardless of the engine.
All the values can be initialized with DbConfig::init_for() method, that uses
environment variables to setup all of them, otherwise all have default values,
except the string connection.
Fields§
§database_url: StringDatabase URL, initialized with the DATABASE_URL env
min_connections: u32Min connections created at start-up, value set with MIN_CONNECTIONS env,
default 1
max_connections: u32Max connections allowed, value set with MAX_CONNECTIONS env,
default 10
acquire_timeout: DurationTime allowed to acquire a connection, value set with ACQUIRE_TIMEOUT_MS env,
default 750 milliseconds
idle_timeout: DurationMax time a connection can be idle, value set with IDLE_TIMEOUT_SEC env,
default 300 sec (5 min).
Any connection that remains in the idle queue longer than this will be closed.
test_before_acquire: boolWhether to test before test the connection at start-up or not,
value set with TEST_BEFORE_ACQUIRE env, default to false
Implementations§
Source§impl DbConfig
impl DbConfig
Sourcepub fn init_for(env: &Environment) -> Result<Self>
pub fn init_for(env: &Environment) -> Result<Self>
Init the object with env passed, and the rest of the
attributes reading its corresponding environment variable,
otherwise use a default value.
The database string is saved in self.database_url with the value found at
the DATABASE_URL environment value, that it’s the only one required (there
is no default value). If env passed is Environment::Test the prefix
_test is added to the string connection, to avoid using by mistake prod/local
databases, unless the string already ends with the prefix, or the string has
connection arguments (the ? symbol in the string).
§Examples
use std::env;
use server_env_config::db::DbConfig;
use server_env_config::env::Environment;
// Configurations should be actually set by the OS environment
env::set_var("DATABASE_URL", "postgresql://user:pass@localhost/db");
env::set_var("MAX_CONNECTIONS", "50");
env::set_var("IDLE_TIMEOUT_SEC", "60");
let db = DbConfig::init_for(&Environment::Local).unwrap();
assert_eq!(db.database_url, "postgresql://user:pass@localhost/db");
assert_eq!(db.max_connections, 50);
// All settings except DATABASE_URL have default values if env variables are not set
assert_eq!(db.min_connections, 1);
assert!(!db.test_before_acquire);
env::remove_var("DATABASE_URL"); // if not set, DbConfig cannot be initialized
let db = DbConfig::init_for(&Environment::Local);
assert!(db.is_err());