asdine / storm

Simple and powerful toolkit for BoltDB
MIT License
2.07k stars 139 forks source link

Get all items of a Bucket #263

Open sh0umik opened 5 years ago

sh0umik commented 5 years ago

When I use Set and Get it requires a bucket name.

db.Set("logs", time.Now(), "I'm eating my breakfast man")
db.Get("logs", someObjectId, &log)

But how can I get all the items in the particular bucket logs ? How to iterate over a bucket elements ?

Proposing Something like

var allLogs []Logs
err := db.GetAll("bucketname", &allLogs)
waveletlet commented 4 years ago

This is similar to https://github.com/asdine/storm/issues/209, but I can't figure out how to do it with the .Each() method mentioned in that discussion (or a db.All()) with a very simple key:value store (string:bool).

The best I've figured out so far is to do a manual Bolt transaction. I only want the keys in my case:

// create db, do some 'db.Set("urls", urlString, true)'
var urls []string
db.Bolt.View(func(tx *bolt.Tx) error {    
  b := tx.Bucket([]byte("urls"))    
  c := b.Cursor()                                         
  for k, v := c.First(); k != nil; k, v = c.Next() {    
    fmt.Printf("key=%s, value=%s\n", k, v)
    urls = append(urls, string(k))  //convert to string because Bolt holds it as []byte
  }    
  return nil    
}) 

Is there any more direct Storm way of doing that?