SeaQL / sea-orm

🐚 An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
6.57k stars 461 forks source link

transaction use probelm with state #2162

Open joebnb opened 3 months ago

joebnb commented 3 months ago

hello

im a new of rust and sea-rom, when i using axum as web server framework have some problem of it.

i using sea-orm connection as axum state of whole app.all was working fine,except transaction.

because it's mutable.but axum state to keep mutex state need RwLock, i think it's will affect performance of muti-thread.

axum mutable state docs: https://github.com/tokio-rs/axum/pull/1759/files#diff-84223c57f305fae05708a2bb1a4009db01ce168ef6d56ba1631ed6e3436507d3

    match query_data.unwrap() {
        Some(data) => {
            let transaction = &_state.conn.begin().await.unwrap(); // here is  &sea_orm::DatabaseTransaction

            let mut data::ActiveModel = data.into();

            let result = data.save(transaction).await;
            transaction.commit().await; // here will throw cannot move out of `*transaction` which is behind a shared reference
// move occurs because `*transaction` has type `DatabaseTransaction`, which does not implement the `Copy` trait

            match result {
                Ok(_) => http::response_basic(Some("()".to_string()), None, None),
                Err(err) => http::response_500(Some(err.to_string())),
            }
        }
        None => http::response_500(Some("no update target found".to_owned())),
    }
// if i change  line 3 to 
  let transaction = &_state.conn.begin().await.unwrap(); // if here is  &&mut sea_orm::DatabaseTransaction this type was not satisify 

// when do save will throw:
  let result = data.save(transaction).await; // the trait bound `&mut DatabaseTransaction: ConnectionTrait` is not satisfied
// the trait `ConnectionTrait` is not implemented for `&mut DatabaseTransaction`

how to use transaction in this case,will it must make a Rwlock when do transaction to stop other thread to use connection ?

https://github.com/SeaQL/sea-orm/pull/2043 i dont know did this will help me