Skip to main content

deadpool_sqlite/
config.rs

1use std::{convert::Infallible, path::PathBuf};
2
3use crate::{CreatePoolError, Manager, Pool, PoolBuilder, PoolConfig, Runtime};
4
5/// Configuration object.
6///
7/// # Example (from environment)
8///
9/// By enabling the `serde` feature you can read the configuration using the
10/// [`config`](https://crates.io/crates/config) crate as following:
11/// ```env
12/// SQLITE__PATH=db.sqlite3
13/// SQLITE__POOL__MAX_SIZE=16
14/// SQLITE__POOL__TIMEOUTS__WAIT__SECS=5
15/// SQLITE__POOL__TIMEOUTS__WAIT__NANOS=0
16/// ```
17/// ```rust
18/// #[derive(serde::Deserialize, serde::Serialize)]
19/// struct Config {
20///     sqlite: deadpool_sqlite::Config,
21/// }
22/// impl Config {
23///     pub fn from_env() -> Result<Self, config::ConfigError> {
24///         let mut cfg = config::Config::builder()
25///            .add_source(config::Environment::default().separator("__"))
26///            .build()?;
27///            cfg.try_deserialize()
28///     }
29/// }
30/// ```
31#[derive(Clone, Debug, Default)]
32#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
33pub struct Config {
34    /// Path to SQLite database file.
35    pub path: PathBuf,
36
37    /// [`Pool`] configuration.
38    pub pool: Option<PoolConfig>,
39}
40
41impl Config {
42    /// Create a new [`Config`] with the given `path` of SQLite database file.
43    #[must_use]
44    pub fn new(path: impl Into<PathBuf>) -> Self {
45        Self {
46            path: path.into(),
47            pool: None,
48        }
49    }
50
51    /// Creates a new [`Pool`] using this [`Config`].
52    ///
53    /// # Errors
54    ///
55    /// See [`CreatePoolError`] for details.
56    pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, CreatePoolError> {
57        self.builder(runtime)
58            .map_err(CreatePoolError::Config)?
59            .build()
60            .map_err(CreatePoolError::Build)
61    }
62
63    /// Creates a new [`PoolBuilder`] using this [`Config`].
64    ///
65    /// # Errors
66    ///
67    /// See [`ConfigError`] for details.
68    pub fn builder(&self, runtime: Runtime) -> Result<PoolBuilder, ConfigError> {
69        let manager = Manager::from_config(self, runtime);
70        Ok(Pool::builder(manager)
71            .config(self.get_pool_config())
72            .runtime(runtime))
73    }
74
75    /// Returns [`deadpool::managed::PoolConfig`] which can be used to construct
76    /// a [`deadpool::managed::Pool`] instance.
77    #[must_use]
78    pub fn get_pool_config(&self) -> PoolConfig {
79        self.pool.unwrap_or_default()
80    }
81}
82
83/// This error is returned if there is something wrong with the SQLite configuration.
84///
85/// This is just a type alias to [`Infallible`] at the moment as there
86/// is no validation happening at the configuration phase.
87pub type ConfigError = Infallible;