如何在 Rocket 环境中建立数据库连接?

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

我为我的 Rocket 应用程序设置了以下工作数据库连接:

main.rs:

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

Rocket.toml:

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

我想从环境中设置用户名、密码和数据库名称。期望它是 ROCKET_MY_DB=postgres://user:pass@localhost/my_db 之类的东西,但它没有用。无法找到 Rocket 的相关数据库示例。

I would like to set username, password and a database name from the environment. Didn't find relevant example for Rocket.

doc

的头版

Rocket and Rocket libraries are configured via the Rocket.toml file and/or ROCKET_{PARAM} environment variables. For more information on how to configure Rocket, see the configuration section of the guide as well as the config module documentation.

Example 只需关注 link:

All configuration parameters, including extras, can be overridden through environment variables. To override the configuration parameter {param}, use an environment variable named ROCKET_{PARAM}. For instance, to override the "port" configuration parameter, you can run your application with:

ROCKET_PORT=3721 ./your_application

  Configured for development.
    => ...
    => port: 3721 ```

经过大量实验(因为没有针对数据库的具体说明,我期望一些看起来更像标准方法的东西:ENV_PARAM=conn_string,即在 Diesel 中)我终于发现我需要将一个复杂的对象放入环境中。

解决方案是这个难看的字符串:

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