Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow nested transactions #19

Open
samvdst opened this issue Aug 7, 2024 · 0 comments
Open

Allow nested transactions #19

samvdst opened this issue Aug 7, 2024 · 0 comments

Comments

@samvdst
Copy link

samvdst commented Aug 7, 2024

I have the need for nested transactions and have already implemented a simple but working solution. I would like to bring this to your attention and double check if this is the desired behavior or not.

Imagine an API handler needs to ensure that an operation across two different BMCs is transactional.

pub async fn some_api_handler(State(mm): State<ModelManager>) -> Result<()> {
    let mm = mm.new_with_txn()?;
    mm.dbx().begin_txn().await?;

    FooBmc::create(&mm, &foo_payload).await?;
    BarBmc::create(&mm, &bar_payload).await?;

    mm.dbx().commit_txn().await?;

    Ok(())
}

However, BarBmc needs to make sure that it's create function is always in a transaction, regardless of whether the calling site already has a running transaction or not.

impl BarBmc {
    pub async fn create(mm: &ModelManager, payload: &BarPayload) -> Result<()> {
        let mm = mm.new_with_txn()?;
        mm.dbx().begin_txn().await?;

        let new_id = base::create::<Self, _>(&mm, payload).await?;
        Self::something_else(&mm, new_id).await?;

        mm.dbx().commit_txn().await?;

        Ok(())
    }
}

If you call BarBmc::create without a transaction, everything will work.

If you call BarBmc::create inside a running transaction, you get a (code: 5) database is locked error (probably only in SQLite).

A simple solution would be that mm.new_with_transaction() should not reset the txn_holder.

pub fn new_with_txn(&self) -> ModelManager {
+    if self.dbx.with_txn() {
+        return ModelManager {
+            dbx: self.dbx.clone(),
+        };
+    };
    let dbx = Dbx::new(self.dbx.db().clone(), true);
    ModelManager { dbx }
}
impl Dbx {
    pub fn new(db_pool: Db, with_txn: bool) -> Self {
        Self {
            db_pool,
            txn_holder: Arc::default(),
            with_txn,
        }
    }
+
+    pub fn with_txn(&self) -> bool {
+        self.with_txn
+    }
}

Let me know what you think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant