Skip to content

Commit

Permalink
Merge pull request #56 from philippgille/improve-db-path-handling
Browse files Browse the repository at this point in the history
Improve NewPersistentDB() path handling
  • Loading branch information
philippgille authored Mar 17, 2024
2 parents f76265c + dd0f31d commit 586406c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 6 deletions.
18 changes: 12 additions & 6 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,19 @@ func NewPersistentDB(path string) (*DB, error) {
}

// If the directory doesn't exist, create it and return an empty DB.
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
err := os.MkdirAll(path, 0o700)
if err != nil {
return nil, fmt.Errorf("couldn't create persistence directory: %w", err)
}
fi, err := os.Stat(path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
err := os.MkdirAll(path, 0o700)
if err != nil {
return nil, fmt.Errorf("couldn't create persistence directory: %w", err)
}

return db, nil
return db, nil
}
return nil, fmt.Errorf("couldn't get info about persistence directory: %w", err)
} else if !fi.IsDir() {
return nil, fmt.Errorf("path is not a directory: %s", path)
}

// Otherwise, read all collections and their documents from the directory.
Expand Down
59 changes: 59 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,70 @@ package chromem

import (
"context"
"math/rand"
"os"
"path/filepath"
"reflect"
"slices"
"testing"
)

func TestNewPersistentDB(t *testing.T) {
t.Run("Create directory", func(t *testing.T) {
randString := randomString(rand.New(rand.NewSource(rand.Int63())), 10)
path := filepath.Join(os.TempDir(), randString)
defer os.RemoveAll(path)

// Path shouldn't exist yet
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("expected path to not exist, got", err)
}

db, err := NewPersistentDB(path)
if err != nil {
t.Fatal("expected no error, got", err)
}
if db == nil {
t.Fatal("expected DB, got nil")
}

// Path should exist now
if _, err := os.Stat(path); err != nil {
t.Fatal("expected path to exist, got", err)
}
})
t.Run("Existing directory", func(t *testing.T) {
path, err := os.MkdirTemp(os.TempDir(), "")
if err != nil {
t.Fatal("couldn't create temp dir:", err)
}
defer os.RemoveAll(path)

db, err := NewPersistentDB(path)
if err != nil {
t.Fatal("expected no error, got", err)
}
if db == nil {
t.Fatal("expected DB, got nil")
}
})
}

func TestNewPersistentDB_Errors(t *testing.T) {
t.Run("Path is an existing file", func(t *testing.T) {
f, err := os.CreateTemp(os.TempDir(), "")
if err != nil {
t.Fatal("couldn't create temp file:", err)
}
defer os.RemoveAll(f.Name())

_, err = NewPersistentDB(f.Name())
if err == nil {
t.Fatal("expected error, got nil")
}
})
}

func TestDB_CreateCollection(t *testing.T) {
// Values in the collection
name := "test"
Expand Down

0 comments on commit 586406c

Please sign in to comment.