launchbadge / sqlx

🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, and SQLite.
Apache License 2.0
13.32k stars 1.27k forks source link

`sqlx::test` macro argument for specifing the database url variable #2220

Open sassman opened 1 year ago

sassman commented 1 year ago

Is your feature request related to a problem? Please describe. sqlx::test macro assumes right now that a database connection can be established from the environment variable DATABASE_URL

Working on an application where one cannot influence the environment variable the application takes.

Describe the solution you'd like It would be very helpful to specify the environment variable name where the database url is actually stored in. Like so:

#[sqlx::test(database_url_env_var = "XXX_DATABASE_URL")]
async fn test_somebasics(pool: PgPool) {
    // test code goes here
} 

Describe alternatives you've considered Alternatively it would also help to specify the name of a function that acts as the Pool creation factory. Like so:

/// this is the pool factory method for tests
async fn create_pool() -> PgPool {
    let url = dotenvy::var("XXX_DATABASE_URL").expect("XXX_DATABASE_URL must be set");

    let master_opts = PgConnectOptions::from_str(&url).expect("failed to parse XXX_DATABASE_URL");

    PoolOptions::new()
        .max_connections(20)
        .after_release(|_conn, _| Box::pin(async move { Ok(false) }))
        .connect_lazy_with(master_opts)
}

#[sqlx::test(pool_factory = "create_pool")]
async fn test_somebasics(pool: PgPool) {
    // test code goes here
} 
nk9 commented 4 months ago

This is very similar to what's being discussed in #3022.