Search code examples
databaserustsettingsrust-rocket

How to set up a database connection from environment in Rocket?


I have following working database connection setup for my Rocket app:

main.rs:

#[database("my_db")]
pub struct DbConn(diesel::PgConnection);

Rocket.toml:

[global.databases]
my_db = { url = "postgres://user:pass@localhost/my_db" }

I would like to set username, password and a database name from the environment. Expected it to be something like ROCKET_MY_DB=postgres://user:pass@localhost/my_db, but it didn't work. Was unable find relevant database example for Rocket.


Solution

  • After a lot of experiments (as there is no specific instructions for the database and I expected something that looked more like a standard approach: ENV_PARAM=conn_string, i.e. in Diesel) I finally figured out that I need to place a complex object into the environment.

    The solution is this ugly string:

    ROCKET_DATABASES={my_db={url="postgres://user:pass@localhost/my_db"}}