kurtbuilds / ormlite

An ORM in Rust for developers that love SQL.
https://crates.io/crates/ormlite
MIT License
216 stars 11 forks source link

[Question] Transactions support roadmap #22

Closed matpaul closed 1 year ago

matpaul commented 1 year ago

Hello, Are you planning to add transactions support? (not exist in roadmap) Thank you

kurtbuilds commented 1 year ago

I haven't planned on this, but I'm open to adding this to the roadmap.

ormlite does a lot of codegen, but at its core is a simple wrapper around sqlx, so I wouldn't be surprised if the sqlx tools for transactions work out of the box. If you try and report back, it'd be helpful for other people wondering the same. We could also update the ormlite readme/docs.

If you have recommendations for what a hypothetical API would look like, happy to take that into consideration when implementing this!

matpaul commented 1 year ago

Okay, I see that sqlx supports transactions (https://docs.rs/sqlx/latest/sqlx/struct.Transaction.html).

Regarding the hypothetical API, it can be similar to Diesel's (https://docs.diesel.rs/master/diesel/connection/trait.Connection.html#method.transaction):

let result = connection.transaction(|conn| {
    let john = Person {
        id: 1,
        name: "John".to_string(),
        age: 99,
    }.insert(&mut conn).await?; // if err -> rollback

    Ok(john) // commit 
});

match result {
    Ok(john) => println!("Transaction completed successfully {}", john.name),
    Err(e) => println!("Transaction failed: {:?}", e),
}
kurtbuilds commented 1 year ago

@matpaul All of the API calls for ormlite and sqlx take the database object (Whether a connection, a pool, or a transaction), so everything should just transparently work.

I can confirm I'm successfully using transactions with ormlite. In my case, it's specifically for tests, so that they run much faster, without committing to database, and are trivial to run in parallel and rollback at test teardown. It works great.

If you run into any bugs or issues doing this, let me know, but for now, I'll consider this issue closed.