Skip to content

Commit

Permalink
mutex add string keys
Browse files Browse the repository at this point in the history
  • Loading branch information
tbdsux committed May 26, 2021
1 parent 0b792aa commit 9a53ca8
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 9 deletions.
2 changes: 1 addition & 1 deletion collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func newMiniCollection(filename string) *MiniCollections {

// Collections creates a new key with an array / slice value.
func (db *MiniDB) Collections(key string) *MiniCollections {
d := db.getOrCreateMutex(key)
d := db.getOrCreateMutex("cols_" + key)
d.Lock()
defer d.Unlock()

Expand Down
2 changes: 1 addition & 1 deletion keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func newMiniDB(dir, filename string) *MiniDB {

// Key creates a new key in the json.
func (db *MiniDB) Key(key string) *MiniDB {
d := db.getOrCreateMutex(key)
d := db.getOrCreateMutex("keys_" + key)
d.Lock()
defer d.Unlock()

Expand Down
12 changes: 10 additions & 2 deletions values-query.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,27 @@ import "errors"

// Update updates the key's value. It returns nil if updated.
func (db *MiniStore) Update(key string, v interface{}) error {
defer db.writeToDB()
d := db.getOrCreateMutex("store_update_" + key)
d.Lock()
defer d.Unlock()

if _, ok := db.store[key]; !ok {
return errors.New("unknown key")
}

db.store[key] = v

db.writeToDB()

return nil
}

// Remove attemps to remove the key from the db if it exists.
// It returns nil if it is removed
func (db *MiniStore) Remove(key string) error {
defer db.writeToDB()
d := db.getOrCreateMutex("store_remove_" + key)
d.Lock()
defer d.Unlock()

if _, ok := db.store[key]; !ok {
return errors.New("key does not exists")
Expand All @@ -27,6 +33,8 @@ func (db *MiniStore) Remove(key string) error {
// remove
delete(db.store, key)

db.writeToDB()

return nil
}

Expand Down
7 changes: 2 additions & 5 deletions values.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package minidb
import (
"encoding/json"
"errors"
"fmt"
"log"
"path"
"sync"
Expand All @@ -29,7 +28,7 @@ func newMiniStore(filename string) *MiniStore {

// Store creates a new key with a given value in the json.
func (db *MiniDB) Store(key string) *MiniStore {
d := db.getOrCreateMutex(key)
d := db.getOrCreateMutex("store_" + key)
d.Lock()
defer d.Unlock()

Expand Down Expand Up @@ -94,9 +93,7 @@ func (db *MiniStore) Write(v interface{}) error {
return err
}

fmt.Println(string(d))

defer json.Unmarshal(d, &db.store)
json.Unmarshal(d, &db.store)

return write(db.db, d)
}

0 comments on commit 9a53ca8

Please sign in to comment.