Skip to content

Allow nested transactions #19

Description

@samvdst

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions