File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -58,15 +58,21 @@ pub async fn load<R: Runtime>(
5858
5959 let mut instances = db_instances. 0 . write ( ) . await ;
6060
61- // Double-check in case another thread loaded it while we waited for write lock
62- if instances. contains_key ( & db) {
63- return Ok ( db) ;
61+ // Use entry API to atomically check and insert, avoiding race conditions
62+ // where two callers could both create wrappers
63+ use std:: collections:: hash_map:: Entry ;
64+ match instances. entry ( db. clone ( ) ) {
65+ Entry :: Occupied ( _) => {
66+ // Another caller won the race and inserted while we waited for write lock
67+ Ok ( db)
68+ }
69+ Entry :: Vacant ( entry) => {
70+ // We won the race, create and insert the wrapper
71+ let wrapper = DatabaseWrapper :: connect ( & db, & app, custom_config) . await ?;
72+ entry. insert ( wrapper) ;
73+ Ok ( db)
74+ }
6475 }
65-
66- let wrapper = DatabaseWrapper :: connect ( & db, & app, custom_config) . await ?;
67- instances. insert ( db. clone ( ) , wrapper) ;
68-
69- Ok ( db)
7076}
7177
7278/// Wait for migrations to complete for a database, if any are registered.
You can’t perform that action at this time.
0 commit comments