2595f88213f479a80873d63fa3c5957f74826d33
[epoint] / store / store.go
1 package store
2
3 // persistent key-value store
4 // multiple key-value store can be managed by a single db connection
5 // each store has a name, before usage the name of the store must be
6 // ensured to exist
7 //
8 // TODO: this is a toy implementation
9
10 import (
11         "os"
12         "path/filepath"
13         "io/ioutil"
14 )
15
16
17 type Conn struct {
18         path string
19 }
20
21 func Open(root string) (c *Conn, err error) {
22         c = new(Conn)
23         c.path, err = filepath.Abs(root)
24         if err != nil {
25                 return
26         }
27         err = os.MkdirAll(c.path, 0755)
28         if err != nil {
29                 return
30         }
31         return
32 }
33
34 func (c *Conn) Get(name, k string) (v []byte, err error) {
35         return ioutil.ReadFile(filepath.Join(c.path, name, k))
36 }
37
38 func (c *Conn) Ensure(name string) (err error) {
39         return os.MkdirAll(filepath.Join(c.path, name), 0755)
40 }
41
42 func (c *Conn) Set(name, k string, v []byte) (err error) {
43         fn := filepath.Join(c.path, name, k)
44         // os.O_SYNC
45         f, err := os.Create(fn+".tmp")
46         if err != nil {
47                 return
48         }
49         defer f.Close()
50         _, err = f.Write(v)
51         if err != nil {
52                 return
53         }
54         err = os.Rename(fn+".tmp", fn)
55         return
56 }
57
58 func (c *Conn) Close() (err error) {
59         return
60 }