Skip to content

Commit

Permalink
database: Add auto-create table(bucket) in BoltDB backend
Browse files Browse the repository at this point in the history
This is in order to auto create tables in case they doesn't exist, it will
only apply for the DbAdd method which will receive a tableID, a key and a
value, we're infering that table must exist, this change make sure that
that table is created.

One the useful cases for this is in the ciao-image, which will dinamically
require new tables(buckets) per tenant or project. It will automatically
create the tenant's table when a new image is registered.

When retrieving all key/value elements from a specific table(bucket),
it will not create the table if it doesn't exist, it will return an empty
array which means that there are no elements from that table.

Signed-off-by: Obed N Munoz <[email protected]>
  • Loading branch information
obedmr committed Mar 9, 2017
1 parent 159e426 commit b5e7703
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions database/boltdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ func (db *BoltDB) DbTablesInit(tables []string) (err error) {

// DbAdd adds a new element to table in Bolt database
func (db *BoltDB) DbAdd(table string, key string, value interface{}) (err error) {

err = db.DB.Update(func(tx *bolt.Tx) error {
var v bytes.Buffer

Expand All @@ -138,7 +137,10 @@ func (db *BoltDB) DbAdd(table string, key string, value interface{}) (err error)

bucket := tx.Bucket([]byte(table))
if bucket == nil {
return fmt.Errorf("Bucket %v not found", table)
bucket, err = tx.CreateBucketIfNotExists([]byte(table))
if err != nil {
return fmt.Errorf("Bucket %v creation failed", table)
}
}

err = bucket.Put([]byte(key), v.Bytes())
Expand Down Expand Up @@ -207,16 +209,19 @@ func (db *BoltDB) DbGetAll(table string, dbTable DbTable) (elements []interface{
err = db.DB.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(table))

err := b.ForEach(func(key, value []byte) error {
vr := bytes.NewReader(value)
elem := dbTable.NewElement()
if err := gob.NewDecoder(vr).Decode(elem); err != nil {
return err
}
elements = append(elements, elem)
return nil
})
return err
if b != nil {
err := b.ForEach(func(key, value []byte) error {
vr := bytes.NewReader(value)
elem := dbTable.NewElement()
if err := gob.NewDecoder(vr).Decode(elem); err != nil {
return err
}
elements = append(elements, elem)
return nil
})
return err
}
return nil
})

return elements, err
Expand Down

0 comments on commit b5e7703

Please sign in to comment.