Search code examples
postgresqlrustrust-rocketrust-sqlx

error originates in the macro `$crate::sqlx_macros::expand_query` which comes from the expansion of the macro `sqlx::query_as`


I want to send query to database, but I faced this error:

this error originates in the macro $crate::sqlx_macros::expand_query which comes from the expansion of the macro sqlx::query_as (in Nightly builds, run with -Z macro-backtrace for more info)

DATABASE_URL must be set to use query macros

I am using the Rocket framework and PostgreSQL.

Code:

#[get("/user/<uuid>", rank = 1, format = "text/plain")]
async fn user(pool: &rocket::State<PgPool>, uuid: &str) -> Result<User, Status> {
    let parsed_uuid = Uuid::parse_str(uuid).map_err(|_| Status::BadRequest)?;
    
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE uuid = $1", parsed_uuid)
        .fetch_one(pool.inner())
        .await;
    user.map_err(|_| Status::NotFound)
}

#[launch]
async fn rocket() -> Rocket<Build> {
    let our_rocket = rocket::build();
    
    let config: Config = our_rocket
        .figment()
        .extract()
        .expect("Incorrect Rocket.toml configuration");

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&config.database_url)
        .await
        .expect("Failed to connect to database");
    
    our_rocket.manage(pool)
}
[dependencies]
rocket = { version = "0.5.0-rc.2", features = ["secrets"] }
sqlx = {version = "0.6.2", features = ["postgres","uuid", "runtime-tokio-rustls"]}

How can i solve that problem?


Solution

  • sqlx uses the database to check if your queries types are correct, to use it's macros you have to define the environment variable DATABASE_URL, use a .env file or provide a sqlx-data.json you can set DATABASE_URL to a database with the schema required, you can run cargo with the appropriate environment setup:

    DATABASE_URL="postgres://your_database_info" cargo (run|build|check|…)