github.com/weaviate/weaviate@v1.24.6/adapters/repos/classifications/repo.go (about) 1 // _ _ 2 // __ _____ __ ___ ___ __ _| |_ ___ 3 // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ 4 // \ V V / __/ (_| |\ V /| | (_| | || __/ 5 // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| 6 // 7 // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. 8 // 9 // CONTACT: hello@weaviate.io 10 // 11 12 package classifications 13 14 import ( 15 "context" 16 "encoding/json" 17 "fmt" 18 "os" 19 20 "github.com/go-openapi/strfmt" 21 "github.com/pkg/errors" 22 "github.com/sirupsen/logrus" 23 "github.com/weaviate/weaviate/adapters/repos/db/helpers" 24 "github.com/weaviate/weaviate/entities/models" 25 "github.com/weaviate/weaviate/usecases/classification" 26 bolt "go.etcd.io/bbolt" 27 ) 28 29 var classificationsBucket = []byte("classifications") 30 31 type Repo struct { 32 logger logrus.FieldLogger 33 baseDir string 34 db *bolt.DB 35 } 36 37 func NewRepo(baseDir string, logger logrus.FieldLogger) (*Repo, error) { 38 r := &Repo{ 39 baseDir: baseDir, 40 logger: logger, 41 } 42 43 err := r.init() 44 return r, err 45 } 46 47 func (r *Repo) DBPath() string { 48 return fmt.Sprintf("%s/classifications.db", r.baseDir) 49 } 50 51 func (r *Repo) keyFromID(id strfmt.UUID) []byte { 52 return []byte(id) 53 } 54 55 func (r *Repo) init() error { 56 if err := os.MkdirAll(r.baseDir, 0o777); err != nil { 57 return errors.Wrapf(err, "create root path directory at %s", r.baseDir) 58 } 59 60 boltdb, err := bolt.Open(r.DBPath(), 0o600, nil) 61 if err != nil { 62 return errors.Wrapf(err, "open bolt at %s", r.DBPath()) 63 } 64 65 err = boltdb.Update(func(tx *bolt.Tx) error { 66 if _, err := tx.CreateBucketIfNotExists(classificationsBucket); err != nil { 67 return errors.Wrapf(err, "create classifications bucket '%s'", 68 string(helpers.ObjectsBucket)) 69 } 70 return nil 71 }) 72 if err != nil { 73 return errors.Wrapf(err, "create bolt buckets") 74 } 75 76 r.db = boltdb 77 78 return nil 79 } 80 81 func (r *Repo) Put(ctx context.Context, classification models.Classification) error { 82 classificationJSON, err := json.Marshal(classification) 83 if err != nil { 84 return errors.Wrap(err, "marshal classification to JSON") 85 } 86 87 return r.db.Update(func(tx *bolt.Tx) error { 88 b := tx.Bucket(classificationsBucket) 89 return b.Put(r.keyFromID(classification.ID), classificationJSON) 90 }) 91 } 92 93 func (r *Repo) Get(ctx context.Context, id strfmt.UUID) (*models.Classification, error) { 94 var classificationJSON []byte 95 r.db.View(func(tx *bolt.Tx) error { 96 b := tx.Bucket(classificationsBucket) 97 classificationJSON = b.Get(r.keyFromID(id)) 98 return nil 99 }) 100 101 if len(classificationJSON) == 0 { 102 return nil, nil 103 } 104 105 var c models.Classification 106 err := json.Unmarshal(classificationJSON, &c) 107 if err != nil { 108 return nil, errors.Wrapf(err, "parse classification from JSON") 109 } 110 111 return &c, nil 112 } 113 114 var _ = classification.Repo(&Repo{})