Error using sqlx query macros in Actix-web with PostgreSQL: DATABASE_URL must be set

595 views Asked by At

I am building a Rust web application using actix-web and sqlx for handling database operations with PostgreSQL. I've created an endpoint to insert new subscriptions into the database using sqlx's query! macro. However, when I attempt to run the application, I encounter the following error:

DATABASE_URL must be set, or cargo sqlx prepare must have been run and .sqlx must exist, to use query macros

Here is the relevant part of the handler function:

#[derive(serde::Deserialize)]
pub struct FormData {
    email: String,
    name: String,
}

pub async fn subscribe(
    form: web::Form<FormData>,
    connection: web::Data<PgConnection>,
) -> HttpResponse {
    sqlx::query!(
        r#"
        INSERT INTO subscriptions (id, email, name, subscribed_at)
        VALUES ($1, $2, $3, $4)
        "#,
        Uuid::new_v4(),
        form.email,
        form.name,
        Utc::now()
    )
    .execute(connection.get_ref())
    .await;
    HttpResponse::Ok().finish()
}

And here is the Cargo.toml for reference:

[dependencies]
actix-web = "4.4.0"
# other dependencies...
sqlx = { version = "0.7", default-features = false, features = ["runtime-tokio-rustls", "macros", "postgres", "uuid", "chrono", "migrate"] }
# other dependencies...

I have set the DATABASE_URL environment variable in my .env file:

DATABASE_URL=postgres://postgres:password@localhost/newsletter

I've also tried running cargo sqlx prepare, but the issue persists. What might be causing this error, and how can I resolve it to use the query! macro correctly?

Update :

this is the content of the .env file :

DATABASE_URL="postgresql://root:xx@xx:123456/postgres"

and this is the main function :

and this is the main function:

mod test;
use rust_web::configuration::get_configuration;
use rust_web::startup::run;
use sqlx::{Connection, PgConnection};
use std::net::TcpListener;
extern crate dotenv;
use dotenv::dotenv;
use std::env;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();
    let configuration = get_configuration().expect("Failed to read configuration.");
    let connection = PgConnection::connect(&configuration.database.connection_string())
        .await
        .expect("Failed to connect to Postgres.");
    let address = format!("127.0.0.1:{}", configuration.application_port);
    let listener = TcpListener::bind(address)?;
    run(listener, connection)?.await
}

in this function it shows me this error :

sqlx::query!()

0

There are 0 answers