commit 654cd518130db0a8ff3dd8f18504257bb4a37dd6
parent 5b6c21880123e4b8fe1aebade60b9aa65b276527
Author: lash <dev@holbrook.no>
Date: Fri, 30 Aug 2024 17:38:52 +0100
Add memory db
Diffstat:
3 files changed, 81 insertions(+), 1 deletion(-)
diff --git a/db/fs.go b/db/fs.go
@@ -32,7 +32,7 @@ func(fdb *FsDb) Get(ctx context.Context, key []byte) ([]byte, error) {
}
f, err := os.Open(fp)
if err != nil {
- return nil, err
+ return nil, NewErrNotFound([]byte(fp))
}
defer f.Close()
b, err := ioutil.ReadAll(f)
diff --git a/db/mem.go b/db/mem.go
@@ -0,0 +1,46 @@
+package db
+
+import (
+ "context"
+ "fmt"
+)
+
+type MemDb struct {
+ BaseDb
+ store map[string][]byte
+}
+
+func(mdb *MemDb) Connect(ctx context.Context, connStr string) error {
+ mdb.store = make(map[string][]byte)
+ return nil
+}
+
+func(mdb *MemDb) toHexKey(key []byte) (string, error) {
+ k, err := mdb.ToKey(key)
+ return fmt.Sprintf("%x", k), err
+}
+
+func(mdb *MemDb) Get(ctx context.Context, key []byte) ([]byte, error) {
+ k, err := mdb.toHexKey(key)
+ if err != nil {
+ return nil, err
+ }
+ v, ok := mdb.store[k]
+ if !ok {
+ return nil, NewErrNotFound([]byte(k))
+ }
+ return v, nil
+}
+
+func(mdb *MemDb) Put(ctx context.Context, key []byte, val []byte) error {
+ k, err := mdb.toHexKey(key)
+ if err != nil {
+ return err
+ }
+ mdb.store[k] = val
+ return nil
+}
+
+func(mdb *MemDb) Close() error {
+ return nil
+}
diff --git a/db/mem_test.go b/db/mem_test.go
@@ -0,0 +1,34 @@
+package db
+
+import (
+ "bytes"
+ "context"
+ "testing"
+)
+
+func TestPutGetMem(t *testing.T) {
+ ctx := context.Background()
+ sid := "ses"
+ db := &MemDb{}
+ db.SetPrefix(DATATYPE_USERSTART)
+ db.SetSession(sid)
+ err := db.Connect(ctx, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = db.Put(ctx, []byte("foo"), []byte("bar"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v, err := db.Get(ctx, []byte("foo"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(v, []byte("bar")) {
+ t.Fatalf("expected value 'bar', found '%s'", v)
+ }
+ _, err = db.Get(ctx, []byte("bar"))
+ if err == nil {
+ t.Fatal("expected get error for key 'bar'")
+ }
+}