insert key into store only if it does not exist
[epoint] / pkg / store / store.go
index a27935c..e476a7e 100644 (file)
@@ -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
 }