At CockroachDB, how do parties and transactions interact?

When should I use lots and when should transactions be used? Can I embed a transaction in a package? Package in transaction?

+6
source share
1 answer

A package is a set of operations that are sent to the server as a unit for efficiency. This is equivalent to sending the same operations as individual requests from different threads. Requests in a batch may be performed out of order, and some operations in a batch may be performed while others do not work.

In Go, packages are produced with a dosing object DB.B and must be passed to DB.Run() . For instance:

 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 a sequential and atomic sequence of operations. Transactions guarantee consistency with all other operations in the system: the results of the transaction cannot be visible until the transaction is completed. Since transactions may need to be repeated, transactions are defined by function objects (usually closures) that can be called multiple times.

In Go, transactions are created using the DB.Tx method. The *client.Tx closes implements a similar DB interface; inside a transaction, you must perform all your operations on this object, and not from the original database. If your function returns an error, the transaction will be aborted; otherwise he will commit. Here is the transactional version of the previous example (but see below for a 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 for the completion of the record “a” before the start of the record “b”, and then waits for the completion of the record “b” before the transaction. This can be made more efficient by using batches within the transaction. Tx.B is the dispenser object, as is DB.B In a transaction, you can run batches using Tx.Run or Tx.Commit . Tx.Commit will execute a transaction if and only if all other operations in the package are successful and more efficient than allowing the transaction to be completed automatically when a close is returned. It is good practice to always do the last operation in a batch transaction executed by Tx.Commit :

 err := db.Tx(func(tx *client.Tx) error { return tx.Commit(tx.B.Put("a", "1").Put("b", "2")) }) 
+8
source

Source: https://habr.com/ru/post/988479/


All Articles