sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

pre-migrate "hook" in `#[sqlx::test]`

Open JustusFluegel opened this issue 1 year ago • 8 comments

In one project I am working on we are using sea-orm migrations to setup our db, and sqlx::test for unit tests. It would be nice if there was some way to execute them before sqlx::test runs the actual test, while still being able to use fixtures.

As supporting sea_orm and any other kind of orm inside sqlx would be pretty unreasonable, the simplest solution I could come up with is basically to add a pre-migrate or post-migrate hook to sqlx::test:

async fn some_init_fn(conn: PgConn) -> () {
    // Do some initializing
}

#[sqlx::test(
    migrations = false,
    pre_migrate = some_init_fn,
    path = "../fixtures",
    scripts(some_fixture)
)]
async fn test(db: PgPool) {
    // test something
}

Alternatively I would probably create some kind of other "test" crate which makes this possible, but that would require doing the same work already done here all over again.

I think this would be a pretty simple addition to implement. If that is welcome, I can create a pr for it as well, just want to have some kind of indication for that so that I don't waste my time on it :)

JustusFluegel avatar Jan 27 '24 12:01 JustusFluegel

Alternatively we could of course make it a bit more flexible, like

#[sqlx::test(
    init_scripts(pre_migrate=foo,post_migrate=bar)
)]

or

#[sqlx::test(
    hooks(...)
)]

or just name it init_script like

#[sqlx::test(init_script=foo)].

JustusFluegel avatar Jan 27 '24 12:01 JustusFluegel

There are other related issues. It would be fantastic to see some general enhancements to the #[sql:: test] and query macros. Namely:

  • support sqlx::any
  • support specifying database_url for a SQL test to allow multiple databases
  • extend query! and query_as! so the database_url can be specified so we can have compile time checking of multiple different dbms and database structures.
  • extra options to init databases for tests

dave42w avatar Jan 28 '24 23:01 dave42w

I would be open to work on those as well if that is welcome

JustusFluegel avatar Jan 29 '24 11:01 JustusFluegel

I would be open to work on those as well if that is welcome

I'd love it however I'm not clear how the maintainers feel about changes like this. I haven't seen a roadmap or much detail about the direction they want sqlx to go.

dave42w avatar Jan 29 '24 13:01 dave42w

yep that's why I am waiting on responses first :)

JustusFluegel avatar Jan 29 '24 17:01 JustusFluegel