go - In CockroachDB, how do batches and transactions interact? -
when should use batches , when should use transactions? can embed transaction in batch? batch in transaction?
a batch collection of operations sent server single unit efficiency. equivalent sending same operations individual requests different threads. requests in batch may executed out of order, , it's possible operations in batch succeed while others fail.
in go, batches created batcher object db.b
, , must passed db.run()
. example:
err := db.run(db.b.put("a", "1").put("b", "2"))
is equivalent to:
_, err1 := db.put("a", "1") _, err2 := db.put("b", "2")
a transaction defines consistent , atomic sequence of operations. transactions guarantee consistency respect other operations in system: results of transaction cannot seen unless , until transaction committed. since transactions may need retried, transactions defined function objects (typically closures) may called multiple times.
in go, transactions created db.tx method. *client.tx
parameter closure implements similar interface db
; inside transaction must perform operations on object instead of original db. if function returns error, transaction aborted; otherwise commit. here transactional version of previous example (but see below more efficient version):
err := db.tx(func(tx *client.tx) error { err := tx.put("a", "1") if err != nil { return err } return tx.put("b", "2") })
the previous example waits "a" write complete before starting "b" write, , waits "b" write complete before committing transaction. possible make more efficient using batches inside transaction. tx.b
batcher object, db.b
. in transaction, can run batches either tx.run
or tx.commit
. tx.commit
commit transaction if , if other operations in batch succeed, , more efficient letting transaction commit automatically when closure returns. practice make last operation in transaction batch executed tx.commit
:
err := db.tx(func(tx *client.tx) error { return tx.commit(tx.b.put("a", "1").put("b", "2")) })
Comments
Post a Comment