boltdb / bolt

An embedded key/value database for Go.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is db.view inside db.update safe for atomic updates (increment value)

lundin opened this issue · comments

Hi!

For the use case of a simple key that holds a counter value that i want to increment.
Can i use a read transcation inside a update transcation and simply increase the read out value and expect this mutation to be concurrently safe or does some kind of CAS needs to be in place ?

Also want to say big thank you, boltdb is amazing! I belive most B2B apps will never reach the limit of bolt thus being the no 1 db for rapid development=)

@lundin You don't have to use a read transaction inside a Update() transaction.
A View() transaction is read only, while a Update() transaction is writable and readable.

You could do that like this:

db.Update(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
        v := b.Get([]byte("myNumber"))
        v++ // not actual code, you have to convert []byte to int first, and then convert back
	err := b.Put([]byte("myNumber"),v)
	return err
})

Hope that helps

Many thanks @mbertschler
It make sense now =)