@@ -2,10 +2,51 @@ use sqlx::PgPool;
22use sqlx:: postgres:: PgPoolOptions ;
33use std:: time:: Duration ;
44
5+ /// Creates a connection pool for a PostgreSQL database.
6+ ///
7+ /// # Arguments
8+ ///
9+ /// * `database_url` - A string slice that holds the database connection URL.
10+ ///
11+ /// # Configuration
12+ ///
13+ /// The connection pool is configured with the following options:
14+ /// - `max_connections`: The maximum number of connections in the pool (set to 5).
15+ /// - `acquire_timeout`: The maximum duration to wait for a connection (set to 3 seconds).
16+ ///
17+ /// # Errors
18+ ///
19+ /// This function returns a `Result` with:
20+ /// - `Ok(PgPool)` if the connection pool is successfully created.
21+ /// - `Err(sqlx::Error)` if there is an error, such as:
22+ /// - The `database_url` is invalid.
23+ /// - The database server is unreachable.
24+ /// - A timeout occurs while acquiring a connection.
25+ ///
26+ /// # Example
27+ ///
28+ /// ```
29+ /// # use your_crate_name::db::create_pool;
30+ /// # use sqlx::PgPool;
31+ /// # async fn example() -> Result<(), sqlx::Error> {
32+ /// let database_url = "postgres://user:password@localhost/dbname";
33+ /// let pool: PgPool = create_pool(database_url).await?;
34+ /// # Ok(())
35+ /// # }
36+ /// ```
537pub async fn create_pool ( database_url : & str ) -> Result < PgPool , sqlx:: Error > {
38+ let max_connections: u32 = std:: env:: var ( "DB_MAX_CONNECTIONS" )
39+ . ok ( )
40+ . and_then ( |v| v. parse ( ) . ok ( ) )
41+ . unwrap_or ( 5 ) ;
42+ let acquire_timeout: u64 = std:: env:: var ( "DB_ACQUIRE_TIMEOUT" )
43+ . ok ( )
44+ . and_then ( |v| v. parse ( ) . ok ( ) )
45+ . unwrap_or ( 3 ) ;
46+
647 PgPoolOptions :: new ( )
7- . max_connections ( 5 )
8- . acquire_timeout ( Duration :: from_secs ( 3 ) )
48+ . max_connections ( max_connections )
49+ . acquire_timeout ( Duration :: from_secs ( acquire_timeout ) )
950 . connect ( database_url)
1051 . await
1152}
0 commit comments