X-Git-Url: http://nsz.repo.hu/git/?a=blobdiff_plain;f=pkg%2Fstore%2Fstore.go;h=e476a7e1b10a3e42e50cff70a8671e10cd6c231d;hb=2646267e4d7f7981e5bf63c18f9e0400e3de2f49;hp=a27935c3a4624f11c39ce3d652d696166a1f89af;hpb=f80876c256a8cbe481133b3e1f23323674c86a93;p=epoint diff --git a/pkg/store/store.go b/pkg/store/store.go index a27935c..e476a7e 100644 --- a/pkg/store/store.go +++ b/pkg/store/store.go @@ -21,10 +21,19 @@ type NotFoundError struct { path string } +type AlreadyExistsError struct { + path string +} + func (e NotFoundError) Error() string { return "not found: " + e.path } +func (e AlreadyExistsError) Error() string { + return "already exists: " + e.path +} + +// Open db connection func Open(root string) (c *Conn, err error) { c = new(Conn) c.path, err = filepath.Abs(root) @@ -38,6 +47,7 @@ func Open(root string) (c *Conn, err error) { return } +// Get the value of k func (c *Conn) Get(name, k string) (v []byte, err error) { v, err = ioutil.ReadFile(filepath.Join(c.path, name, k)) if err != nil { @@ -48,10 +58,12 @@ func (c *Conn) Get(name, k string) (v []byte, err error) { return } +// Ensure k-v store with the given name exists func (c *Conn) Ensure(name string) (err error) { return os.MkdirAll(filepath.Join(c.path, name), 0755) } +// Set k to v func (c *Conn) Set(name, k string, v []byte) (err error) { fn := filepath.Join(c.path, name, k) f, err := os.OpenFile(fn+".tmp", os.O_CREATE|os.O_TRUNC|os.O_WRONLY|os.O_SYNC, 0666) @@ -67,6 +79,25 @@ func (c *Conn) Set(name, k string, v []byte) (err error) { return } +// Set k to v, but fail if k already exists +func (c *Conn) Insert(name, k string, v []byte) (err error) { + fn := filepath.Join(c.path, name, k) + f, err := os.OpenFile(fn, os.O_CREATE|os.O_EXCL|os.O_WRONLY|os.O_SYNC, 0666) + if err != nil { + if p, ok := err.(*os.PathError); ok && p.Err == os.EEXIST { + err = AlreadyExistsError{name + "/" + k} + } + return + } + defer f.Close() + _, err = f.Write(v) + if err != nil { + return + } + return +} + +// Append v to value of k func (c *Conn) Append(name, k string, v []byte) (err error) { fn := filepath.Join(c.path, name, k) f, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_SYNC, 0666) @@ -78,6 +109,7 @@ func (c *Conn) Append(name, k string, v []byte) (err error) { return } +// Close db connection func (c *Conn) Close() (err error) { return }