tidwall / buntdb

BuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support or workaround for autoincr?

91doi opened this issue · comments

e.g. for ID of uint

Are you referring to an auto increment identifier, like in SQL?
BuntDB does not have builtin auto increment type.

But you can create your own though.

For example, you can make a helper function that will manage your autoincr type, like this:

func autoincr(tx *buntdb.Tx, name string) (uint64, error) {
	key := "autoincr:" + name
	v, err := tx.Get(key)
  	if err != nil {
  		if err == buntdb.ErrNotFound {
  			_, _, err := tx.Set(key, "1", nil)
  			return 1, err		
  		}
  		return 0, err
  	}
  	x, err := strconv.ParseUint(v, 10, 64)
  	if err != nil {
  		return 0, err
  	}
  	x++
  	_, _, err := tx.Set(key, strconv.FormatUint(x, 10), nil)
  	return x, err
}

And then every time you need a new autoincr id value you can do the following from an Update transaction.

db.Update(func(tx *buntdb.Tx) error {
	id, err := autoincr(tx, "my_id")
	// do something with "id"
	return err
})