Rocket: Share pooled database connection outside rocket http handlers

Created on 17 Dec 2019  路  6Comments  路  Source: SergioBenitez/Rocket

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?

deficiency

Most helpful comment

If you're already in a request guard, you can use request.guard::<ConnectionType>() to get a connection.

All 6 comments

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:

  • The name of this hidden type is technically an implementation detail.
  • IIRC there's no way to get an 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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lucklove picture lucklove  路  4Comments

PSeitz picture PSeitz  路  3Comments

ndarilek picture ndarilek  路  3Comments

kitsuneninetails picture kitsuneninetails  路  4Comments

klnusbaum picture klnusbaum  路  4Comments