Skip to content

Commit

Permalink
Transaction (SeaQL/sea-orm#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Oct 18, 2021
1 parent f04bd90 commit 2bae078
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions SeaORM/docs/01-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@

6.5 [More joins](/docs/advanced-query/more-join)

6.6 [Transaction](/docs/advanced-query/transaction)

7. Internal Design

7.1 [Traits and Types](/docs/internal-design/trait-and-type)
Expand Down
58 changes: 58 additions & 0 deletions SeaORM/docs/07-advanced-query/06-transaction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Transaction

You can perform atomic operations inside transaction. There are two transaction APIs available to you.

## `Closure` style

Transaction will be committed if the closure returned `Ok`, rollbacked if `Err`.

```rust
db.transaction::<_, _, DbErr>(|txn| {
Box::pin(async move {
bakery::ActiveModel {
name: Set("SeaSide Bakery".to_owned()),
profit_margin: Set(10.4),
..Default::default()
}
.save(txn)
.await?;

bakery::ActiveModel {
name: Set("Top Bakery".to_owned()),
profit_margin: Set(15.0),
..Default::default()
}
.save(txn)
.await?;

Ok(())
})
})
.await;
```

## `Begin` ... `commit` / `rollback` style

`Begin` the transaction followed by `commit` or `rollback`. If `txn` goes out of scope, it'd automatically rollback.

```rust
let txn = db.begin().await?;

bakery::ActiveModel {
name: Set("SeaSide Bakery".to_owned()),
profit_margin: Set(10.4),
..Default::default()
}
.save(&txn)
.await?;

bakery::ActiveModel {
name: Set("Top Bakery".to_owned()),
profit_margin: Set(15.0),
..Default::default()
}
.save(&txn)
.await?;

txn.commit().await?;
```

0 comments on commit 2bae078

Please sign in to comment.