github.com/safing/portbase@v0.19.5/database/boilerplate_test.go (about) 1 package database 2 3 import ( 4 "fmt" 5 "sync" 6 7 "github.com/safing/portbase/database/record" 8 ) 9 10 type Example struct { 11 record.Base 12 sync.Mutex 13 14 Name string 15 Score int 16 } 17 18 var exampleDB = NewInterface(&Options{ 19 Internal: true, 20 Local: true, 21 }) 22 23 // GetExample gets an Example from the database. 24 func GetExample(key string) (*Example, error) { 25 r, err := exampleDB.Get(key) 26 if err != nil { 27 return nil, err 28 } 29 30 // unwrap 31 if r.IsWrapped() { 32 // only allocate a new struct, if we need it 33 newExample := &Example{} 34 err = record.Unwrap(r, newExample) 35 if err != nil { 36 return nil, err 37 } 38 return newExample, nil 39 } 40 41 // or adjust type 42 newExample, ok := r.(*Example) 43 if !ok { 44 return nil, fmt.Errorf("record not of type *Example, but %T", r) 45 } 46 return newExample, nil 47 } 48 49 func (e *Example) Save() error { 50 return exampleDB.Put(e) 51 } 52 53 func (e *Example) SaveAs(key string) error { 54 e.SetKey(key) 55 return exampleDB.PutNew(e) 56 } 57 58 func NewExample(key, name string, score int) *Example { 59 newExample := &Example{ 60 Name: name, 61 Score: score, 62 } 63 newExample.SetKey(key) 64 return newExample 65 }