1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16
17
18
19 package kvutil
20
21 import (
22 "fmt"
23 "io"
24 "os"
25 "strconv"
26
27 "go4.org/lock"
28 "modernc.org/kv"
29 )
30
31
32
33 func Open(dbFile string, opts *kv.Options) (*kv.DB, error) {
34 createOpen := kv.Open
35 verb := "opening"
36 if _, err := os.Stat(dbFile); os.IsNotExist(err) {
37 createOpen = kv.Create
38 verb = "creating"
39 }
40 if opts == nil {
41 opts = &kv.Options{}
42 }
43 if opts.Locker == nil {
44 opts.Locker = func(dbFile string) (io.Closer, error) {
45 lkfile := dbFile + ".lock"
46 cl, err := lock.Lock(lkfile)
47 if err != nil {
48 return nil, fmt.Errorf("failed to acquire lock on %s: %v", lkfile, err)
49 }
50 return cl, nil
51 }
52 }
53 if v, _ := strconv.ParseBool(os.Getenv("CAMLI_KV_VERIFY")); v {
54 opts.VerifyDbBeforeOpen = true
55 opts.VerifyDbAfterOpen = true
56 opts.VerifyDbBeforeClose = true
57 opts.VerifyDbAfterClose = true
58 }
59 db, err := createOpen(dbFile, opts)
60 if err != nil {
61 return nil, fmt.Errorf("error %s %s: %v", verb, dbFile, err)
62 }
63 return db, nil
64 }