-
-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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?; | ||
``` |