level-db golang实现写入现有值?

时间:2013-09-16 16:51:15

标签: go leveldb

我正在尝试使用leveldb-g实现并遇到一些问题。

这是我的实现(基于另一个答案here

package propertyData

import (
    "code.google.com/p/leveldb-go/leveldb/db"
    "code.google.com/p/leveldb-go/leveldb/table"
    "log"
    "runtime"
)

const (
    DBFILE = "./admin.db"
)

var DBFS = db.DefaultFileSystem

func AddDataToProperty(property, value string) {
    Connection, e := DBFS.Create(DBFILE)
    Check(e)
    w := table.NewWriter(Connection, nil)
    defer w.Close()

    e = w.Set([]byte(property), []byte(value), nil)
}

func GetDataFromProperty(property string) string {

    v := findOne([]byte(property))

    return string(v)
}

func findOne(k []byte) []byte {
    Connection, e := DBFS.Open(DBFILE)
    Check(e)
    r := table.NewReader(Connection, nil)
    v1, err := r.Get([]byte(k), nil)
    if err != nil {
        log.Fatalf("An error occurred finding one", err.Error())
    }

    return v1

}

func Check(e error) {
    if e != nil {
        _, file, line, _ := runtime.Caller(1)
        log.Fatalf("Bad Happened: %s, %s", file, line)
    }
}

和测试:

package propertyData

import (
    "com.levelsbeyond/admin/propertyData"
    "log"
    "os"
    "testing"
)

func TestAddProperty(t *testing.T) {
    os.RemoveAll("./admin.db")

    propertyData.AddDataToProperty("test.property", "one")
    propertyData.AddDataToProperty("test.property", "two")
    propertyData.AddDataToProperty("test.property", "three")

    propertyValue := propertyData.GetDataFromProperty("test.property")
    log.Println(propertyValue)

    propertyData.AddDataToProperty("test.different", "four")
    propertyValue = propertyData.GetDataFromProperty("test.different")
    log.Println(propertyValue)

    propertyValue = propertyData.GetDataFromProperty("test.property")
    log.Println(propertyValue)

}

哪个输出:

=== RUN TestAddProperty
2013/09/16 10:47:50 three
2013/09/16 10:47:50 four
2013/09/16 10:47:50 
--- PASS: TestAddProperty (0.00 seconds)

就像写第二个属性(“property.different”)一样,覆盖我已有的值。我确定我做的事情很愚蠢,任何帮助都会非常感激。

修改

我在findOne函数中添加了一些错误处理(感谢@miltonb),我实际上遇到了错误,但我不知道该怎么做:

=== RUN TestAddProperty
2013/09/16 15:36:34 three
2013/09/16 15:36:34 four
2013/09/16 15:36:34 An error occurred finding one%!(EXTRA string=leveldb/db: not found)
exit status 1
FAIL    command-line-arguments  0.018s

1 个答案:

答案 0 :(得分:2)

使用levidb http://godoc.org/github.com/jmhodges/levigo等更好的文档更改为leveldb的另一个实现。