add tests; add version and removeDb procedures

This commit is contained in:
Xie Yanbo 2019-11-09 11:52:46 +08:00
parent 388514f895
commit ba4f8cd3b4
1 changed files with 51 additions and 23 deletions

View File

@ -12,8 +12,8 @@ type
LevelDbException* = object of Exception LevelDbException* = object of Exception
const const
levelDbTrue = cuchar(1) levelDbTrue = uint8(1)
levelDbFalse = cuchar(0) levelDbFalse = uint8(0)
proc checkError(errPtr: cstring) = proc checkError(errPtr: cstring) =
if errPtr != nil: if errPtr != nil:
@ -46,6 +46,10 @@ proc open*(path: string): LevelDb =
result.db = leveldb_open(options, path, addr errPtr) result.db = leveldb_open(options, path, addr errPtr)
checkError(errPtr) checkError(errPtr)
proc version*(self: LevelDb): (int, int) =
result[0] = leveldb_major_version()
result[1] = leveldb_minor_version()
proc put*(self: LevelDb, key: string, value: string, sync = true) = proc put*(self: LevelDb, key: string, value: string, sync = true) =
assert self.db != nil assert self.db != nil
var errPtr: cstring = nil var errPtr: cstring = nil
@ -116,30 +120,54 @@ iterator iter*(self: LevelDb, seek: string = "", reverse: bool = false): (
else: else:
leveldb_iter_next(iterPtr) leveldb_iter_next(iterPtr)
proc removeDb*(name: string) =
var err: cstring = nil
let options = leveldb_options_create()
leveldb_destroy_db(options, name, addr err)
checkError(err)
when isMainModule: when isMainModule:
let db = leveldb.open("test.db") import sequtils
let env = leveldb_create_default_env()
let dbName = $(leveldb_env_get_test_directory(env))
let db = leveldb.open(dbName)
block version:
let (major, minor) = db.version()
doAssert major > 0
doAssert minor > 0
block getPutDelete:
doAssert db.get("hello") == none(string)
db.put("hello", "world") db.put("hello", "world")
echo db.get("nothing") doAssert db.get("hello") == some("world")
echo db.get("hello")
db.delete("hello") db.delete("hello")
echo db.get("hello") doAssert db.get("hello") == none(string)
db.put("aaa", "1") block iter:
db.put("aba", "2") db.put("aa", "1")
db.put("abb", "3") db.put("ba", "2")
db.put("bb", "3")
echo ">> iter" block iterNormal:
for i in db.iter: doAssert toSeq(db.iter()) ==
echo i @[("aa", "1"), ("ba", "2"), ("bb", "3")]
echo ">> iter reverse" block iterReverse:
for i in db.iter(reverse = true): doAssert toSeq(db.iter(reverse = true)) ==
echo i @[("bb", "3"), ("ba", "2"), ("aa", "1")]
echo ">> iter seek ab" block iterSeek:
for i in db.iter(seek = "ab"): doAssert toSeq(db.iter(seek = "ab")) ==
echo i @[("ba", "2"), ("bb", "3")]
echo ">> iter seek ab reverse" block iterSeekReverse:
for i in db.iter(seek = "ab", reverse = true): doAssert toSeq(db.iter(seek = "ab", reverse = true)) ==
echo i @[("ba", "2"), ("aa", "1")]
block close:
db.close()
block remove:
removeDb(dbName)