Skip to main content

rust_ef_postgres/
di_extension.rs

1use crate::tls::PgTlsMode;
2use rust_ef::provider::IDatabaseProvider;
3use std::sync::Arc;
4
5pub trait DbContextOptionsBuilderExt {
6    /// Registers a PostgreSQL provider with a default pool size of 5.
7    fn use_postgres(&mut self, connection_string: &str) -> &mut Self;
8
9    /// Registers a PostgreSQL provider with a configurable pool size.
10    /// `pool_size = 0` uses the deadpool default (CPU count).
11    fn use_postgres_with_pool(&mut self, connection_string: &str, pool_size: usize) -> &mut Self;
12
13    /// Registers a PostgreSQL provider with configurable TLS.
14    ///
15    /// `PgTlsMode::Disable` is equivalent to [`DbContextOptionsBuilderExt::use_postgres_with_pool`].
16    /// `PgTlsMode::Require(connector)` enforces TLS for all pooled connections
17    /// using the platform's native TLS implementation.
18    fn use_postgres_with_tls(
19        &mut self,
20        connection_string: &str,
21        pool_size: usize,
22        tls: PgTlsMode,
23    ) -> &mut Self;
24}
25
26impl DbContextOptionsBuilderExt for rust_ef::db_context::DbContextOptionsBuilder {
27    fn use_postgres(&mut self, connection_string: &str) -> &mut Self {
28        self.use_postgres_with_pool(connection_string, 5)
29    }
30
31    fn use_postgres_with_pool(&mut self, connection_string: &str, pool_size: usize) -> &mut Self {
32        let cs = connection_string.to_string();
33        self.set_provider_factory(
34            "postgres",
35            &cs,
36            Arc::new(move |cs: &str| {
37                Ok(
38                    Arc::new(crate::provider::PostgresProvider::new(cs, pool_size)?)
39                        as Arc<dyn IDatabaseProvider>,
40                )
41            }),
42        )
43    }
44
45    fn use_postgres_with_tls(
46        &mut self,
47        connection_string: &str,
48        pool_size: usize,
49        tls: PgTlsMode,
50    ) -> &mut Self {
51        let cs = connection_string.to_string();
52        self.set_provider_factory(
53            "postgres",
54            &cs,
55            Arc::new(move |cs: &str| {
56                Ok(Arc::new(crate::provider::PostgresProvider::new_with_tls(
57                    cs,
58                    pool_size,
59                    tls.clone(),
60                )?) as Arc<dyn IDatabaseProvider>)
61            }),
62        )
63    }
64}