bolt icon indicating copy to clipboard operation
bolt copied to clipboard

Renaming, moving, copying Buckets

Open EtienneBruines opened this issue 10 years ago • 2 comments
trafficstars

Hi,

I was wondering what the best practice is with (buckets):

  • renaming;
  • moving;
  • copying;

I want to "simply" rename a bucket, but there was no function for that. I tried moving it, but that didn't have a function either. Then I wanted to copy the bucket (and delete the original afterwards), but that didn't work as planned.

I attempted to do something, but it has several limitations:

  • ~~stats aren't copied (unless they are a part of the .ForEach loop?;~~ nonsense... the statistics are about the data, not about the data being accessed (meaning: copying the data, would actually "copy" the stats)
  • looks very resource-consuming (but as a "simple" rename would require the data to be moved around anyway, then this probably is rather efficient);
// moveBucket moves the inner bucket with key 'oldkey' to a new bucket with key 'newkey'
// must be used within an Update-transaction
func moveBucket(oldParent, newParent *bolt.Bucket, oldkey, newkey []byte) error {
    oldBuck := oldParent.Bucket(oldkey)
    newBuck, err := newParent.CreateBucket(newkey)
    if err != nil {
        return err
    }

    err = oldBuck.ForEach(func(k, v []byte) error {
        if v == nil {
            // Nested bucket
            return moveBucket(oldBuck, newBuck, k, k)
        } else {
            // Regular value
            return newBuck.Put(k, v)
        }
    })
    if err != nil {
        return err
    }

    return oldParent.DeleteBucket(oldkey)
}

Would this be the way to go, or is there some idiomatic boltdb method that fits better?

EtienneBruines avatar Jul 08 '15 21:07 EtienneBruines

How would this work for a root level bucket?

sanbornm avatar Oct 26 '16 17:10 sanbornm

I too find myself in need of a way to rename buckets.

josharian avatar Dec 06 '16 23:12 josharian