mirror of
https://github.com/etcd-io/bbolt.git
synced 2025-05-31 11:42:30 +00:00
Add CreateBucketIfNotExists().
This commit is contained in:
parent
092b63f25e
commit
63e8e474d7
8
db.go
8
db.go
@ -389,6 +389,14 @@ func (db *DB) CreateBucket(name string) error {
|
||||
})
|
||||
}
|
||||
|
||||
// CreateBucketIfNotExists creates a new bucket with the given name if it doesn't already exist.
|
||||
// This function can return an error if the name is blank, or the bucket name is too long.
|
||||
func (db *DB) CreateBucketIfNotExists(name string) error {
|
||||
return db.Do(func(t *RWTransaction) error {
|
||||
return t.CreateBucketIfNotExists(name)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteBucket removes a bucket from the database.
|
||||
// Returns an error if the bucket does not exist.
|
||||
func (db *DB) DeleteBucket(name string) error {
|
||||
|
@ -49,6 +49,16 @@ func (t *RWTransaction) CreateBucket(name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
|
||||
// Returns an error if the bucket name is blank, or if the bucket name is too long.
|
||||
func (t *RWTransaction) CreateBucketIfNotExists(name string) error {
|
||||
err := t.CreateBucket(name)
|
||||
if err != nil && err != ErrBucketExists {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteBucket deletes a bucket.
|
||||
// Returns an error if the bucket cannot be found.
|
||||
func (t *RWTransaction) DeleteBucket(name string) error {
|
||||
|
@ -44,6 +44,19 @@ func TestRWTransactionCreateBucket(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure that a bucket can be created if it doesn't already exist.
|
||||
func TestRWTransactionCreateBucketIfNotExists(t *testing.T) {
|
||||
withOpenDB(func(db *DB, path string) {
|
||||
assert.NoError(t, db.CreateBucketIfNotExists("widgets"))
|
||||
assert.NoError(t, db.CreateBucketIfNotExists("widgets"))
|
||||
|
||||
// Read the bucket through a separate transaction.
|
||||
b, err := db.Bucket("widgets")
|
||||
assert.NotNil(t, b)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure that a bucket cannot be created twice.
|
||||
func TestRWTransactionRecreateBucket(t *testing.T) {
|
||||
withOpenDB(func(db *DB, path string) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user