sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Add support to #[sqlx::test] for sqlx::AnyPool

Open dave42w opened this issue 2 years ago • 0 comments

I am writing a crate axum-tenancy that I would like be as database agnostic as possible. Therefore I would prefer to use sqlx::Any* functionality as much as possible.

Currently when writing tests I have 2 limitations

1. Currently I have to use a specific database pool rather than the AnyPool. This is what I would like to write:

#[cfg(test)]
use sqlx::AnyPool;

#[sqlx::test(migrations = "migrations/postgres")]
async fn check_insert_method(pool: AnyPool) -> sqlx::Result<(), sqlx::Error> {
    let tx: &mut sqlx::Transaction<'_, sqlx::Any> = &mut pool.begin().await?;

    // test that you can insert a user but not insert a duplicxate user
    assert_eq!(insert(tx, "Dave", "Dave Warnock", true, "[email protected]", "01234567891").await.is_ok(), true);
    assert_eq!(insert(tx, "Dave", "Dave Warnock", true, "[email protected]", "01234567891").await.is_err(), true);
    Ok(())
}

However, it appears that currently #[sqlx::test] does not support use sqlx::AnyPool

error[E0277]: the trait bound `sqlx::Any: TestSupport` is not satisfied
   --> axum-tenancy/src/admin/user.rs:117:1
    |
117 | #[sqlx::test(migrations = "migrations/postgres")]
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TestSupport` is not implemented for `sqlx::Any`
    |
    = help: the following other types implement trait `TestSupport`:
              Sqlite
              Postgres
    = note: required for `fn(Pool<sqlx::Any>) -> impl std::future::Future<Output = Result<(), sqlx::Error>>` to implement `sqlx::testing::TestFn`
    = note: this error originates in the attribute macro `sqlx::test` (in Nightly builds, run with -Z macro-backtrace for more info)

Can sqlx::AnyPool support be added to #[sqlx::test]? I assume that as part of the automatic setup #[sqlx::test] would need to call sqlx::any::install_default_drivers();

2. All my tests have to use the same DATABASE_URL as #[sqlx::test] only reads it from the environment.

I would like to be able to specify a DATABASE_URL for each test, just as I can specify a migration. eg

Run a test on postgres and then the same test on sqlite

#[cfg(test)]
use sqlx::AnyPool;

#[sqlx::test(migrations = "migrations/postgres", database_url = "postgresql://localhost?dbname=axum-tenancy&user=dave&password=testing")]
async fn pg_check_insert_method(pool: AnyPool) -> sqlx::Result<(), sqlx::Error> {
    ...
}

#[sqlx::test(migrations = "migrations/sqlite", database_url = "sqlite:axum-tenancy.sqlite?mode=rwc")]
async fn sqlite_check_insert_method(pool: AnyPool) -> sqlx::Result<(), sqlx::Error> {
   ...
}

dave42w avatar Jan 25 '24 06:01 dave42w