@@ -3,8 +3,13 @@ use axum::{
33} ;
44use mysql:: { Opts , Pool } ;
55use std:: env;
6+ use std:: sync:: OnceLock ;
67
7- pub fn connect_to_database ( ) -> Result < mysql:: PooledConn , ( StatusCode , String ) > {
8+ // Pool global usando OnceLock para inicialização única
9+ static DB_POOL : OnceLock < Pool > = OnceLock :: new ( ) ;
10+
11+
12+ pub fn init_db_pool ( ) -> Result < ( ) , ( StatusCode , String ) > {
813 let db_url = env:: var ( "DB_URL" ) . map_err ( |_| {
914 (
1015 StatusCode :: INTERNAL_SERVER_ERROR ,
@@ -26,14 +31,28 @@ pub fn connect_to_database() -> Result<mysql::PooledConn, (StatusCode, String)>
2631 )
2732 } ) ?;
2833
29- let conn = pool . get_conn ( ) . map_err ( |_| {
34+ DB_POOL . set ( pool ) . map_err ( |_| {
3035 (
3136 StatusCode :: INTERNAL_SERVER_ERROR ,
32- "Falha ao obter conexão do pool" . to_string ( ) ,
37+ "Falha ao configurar o pool global " . to_string ( ) ,
3338 )
34- } ) ?;
39+ } )
40+ }
41+
3542
36- Ok ( conn)
43+
44+ pub fn connect_to_database ( ) -> Result < mysql:: PooledConn , ( StatusCode , String ) > {
45+ let pool = DB_POOL . get ( ) . ok_or ( (
46+ StatusCode :: INTERNAL_SERVER_ERROR ,
47+ "Pool de conexões não inicializado" . to_string ( ) ,
48+ ) ) ?;
49+
50+ pool. get_conn ( ) . map_err ( |_| {
51+ (
52+ StatusCode :: INTERNAL_SERVER_ERROR ,
53+ "Falha ao obter conexão do pool" . to_string ( ) ,
54+ )
55+ } )
3756}
3857
3958
0 commit comments