Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support or workaround for autoincr? #81

Open
91doi opened this issue Jan 16, 2022 · 1 comment
Open

Support or workaround for autoincr? #81

91doi opened this issue Jan 16, 2022 · 1 comment

Comments

@91doi
Copy link

91doi commented Jan 16, 2022

e.g. for ID of uint

@tidwall
Copy link
Owner

tidwall commented Jan 20, 2022

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
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants