Rocket can create and manage a pooled database connection which can be accessed inside HTTP handlers.
Can I access this database pool outside these handlers?
Not easily, unfortunately. The code generated by #[database] creates a hidden type for the connection pool and puts it in managed state, which makes sharing hard for two reasons:
Arc<Pool> out, just an &Pool or State<'_, Pool> that is tied to the lifetime of the Rocket instance. This makes it impossible to call launch(), which moves the Rocket instance.In case you only need a single connection before launch (e.g. for initialization), get_one does currently exist for that purpose.
Follow-up question: so you've got get_one, but that requires a Rocket instance. What if you have a request guard that requires a database connection? How do you get the Rocket instance that the connection pool was created for?
If you're already in a request guard, you can use request.guard::<ConnectionType>() to get a connection.
Worked perfectly - thank you!
@cassc Do you have a case where you need access to the actual pool as opposed to a connection from the pool (which we allow, via get_one())?
@SergioBenitez
My application has an HTTP server and also a UDP server, both need to access the database.
Most helpful comment
If you're already in a request guard, you can use
request.guard::<ConnectionType>()to get a connection.