Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 5accf28

Browse files
committed
enhc: update example for nested buckets
1 parent 074dffc commit 5accf28

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,55 @@ func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
464464
func (*Bucket) DeleteBucket(key []byte) error
465465
```
466466

467+
Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
468+
469+
```go
470+
471+
// createUser creates a new user in the given account.
472+
func createUser(accountID int, u *User) error {
473+
// Start the transaction.
474+
tx, err := db.Begin(true)
475+
if err != nil {
476+
return err
477+
}
478+
defer tx.Rollback()
479+
480+
// Retrieve the root bucket for the account.
481+
// Assume this has already been created when the account was set up.
482+
root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
483+
484+
// Setup the users bucket.
485+
bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
486+
if err != nil {
487+
return err
488+
}
489+
490+
// Generate an ID for the new user.
491+
userID, err := bkt.NextSequence()
492+
if err != nil {
493+
return err
494+
}
495+
u.ID = userID
496+
497+
// Marshal and save the encoded user.
498+
if buf, err := json.Marshal(u); err != nil {
499+
return err
500+
} else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
501+
return err
502+
}
503+
504+
// Commit the transaction.
505+
if err := tx.Commit(); err != nil {
506+
return err
507+
}
508+
509+
return nil
510+
}
511+
512+
```
513+
514+
515+
467516

468517
### Database backups
469518

0 commit comments

Comments
 (0)