Execute statements within a transaction
masterThere are two ways to handle transactions in Donald:
- Batching: Use
Db.batchorDb.Async.batch. This processes the entire block in an all-or-none fashion. - Explicit Control: Use
TryBeginTransaction(),TryCommit(), andTryRollback()on the connection or transaction object.TryBeginTransaction()safely starts a transaction or throwsCouldNotBeginTransactionError.
When using explicit transactions, use Db.newCommandForTransaction to create commands associated with that transaction.
// Option 1: Batching
conn
|> Db.batch (fun tran ->
for fullName in [ "John Doe"; "Jane Doe" ] do
tran
|> Db.newCommandForTransaction "INSERT INTO author (full_name) VALUES (@full_name)"
|> Db.setParams ["full_name", SqlType.String fullName ]
|> Db.exec)
// Option 2: Explicit control
use tran = conn.TryBeginTransaction()
for fullName in [ "John Doe"; "Jane Doe" ] do
tran
|> Db.newCommandForTransaction "INSERT INTO author (full_name) VALUES (@full_name)"
|> Db.setParams ["full_name", SqlType.String fullName ]
|> Db.exec
tran.TryCommit ()