From 9dc532b856b9b307158f578435473161e3f045c5 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 14 May 2024 09:48:46 +0200 Subject: [PATCH] Adds support for skips and limits to queryIter --- leveldbstatic.nim | 29 ++++++++++++++++++++--------- tests/test.nim | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/leveldbstatic.nim b/leveldbstatic.nim index b4732fc..4dcb186 100644 --- a/leveldbstatic.nim +++ b/leveldbstatic.nim @@ -426,25 +426,37 @@ proc getIterValue(iterPtr: ptr leveldb_iterator_t): string = str = leveldb_iter_value(iterPtr, addr len) return newString(str, len) -proc queryIter*(self: LevelDb, prefix: string = "", keysOnly: bool = false): LevelDbQueryIter = - var iterPtr = leveldb_create_iterator(self.db, self.readOptions) - +proc seekToQueryStart(iterPtr: ptr leveldb_iterator_t, prefix: string, skip: int) = if prefix.len > 0: leveldb_iter_seek(iterPtr, prefix, prefix.len.csize_t) else: leveldb_iter_seek_to_first(iterPtr) + for i in 0.. 0 and remaining == 0): + iter.closeIter(iterPtr) return emptyResponse + if limit > 0: + dec remaining let keyStr = getIterKey(iterPtr) @@ -460,8 +472,7 @@ proc queryIter*(self: LevelDb, prefix: string = "", keysOnly: bool = false): Lev if keyStr.startsWith(prefix): return (keyStr, valueStr) else: - iter.finished = true - leveldb_iter_destroy(iterPtr) + iter.closeIter(iterPtr) return emptyResponse else: return (keyStr, valueStr) diff --git a/tests/test.nim b/tests/test.nim index fed6e69..858e993 100644 --- a/tests/test.nim +++ b/tests/test.nim @@ -241,6 +241,28 @@ suite "leveldb queryIter": iter.next() == empty iter.finished + test "skip": + let iter = db.queryIter(skip = 1) + check: + not iter.finished + iter.next() == (k2, v2) + not iter.finished + iter.next() == (k3, v3) + not iter.finished + iter.next() == empty + iter.finished + + test "limit": + let iter = db.queryIter(limit = 2) + check: + not iter.finished + iter.next() == (k1, v1) + not iter.finished + iter.next() == (k2, v2) + not iter.finished + iter.next() == empty + iter.finished + test "iterates only keys": let iter = db.queryIter(keysOnly = true) check: @@ -265,6 +287,24 @@ suite "leveldb queryIter": iter.next() == empty iter.finished + test "iterates only 'k', skip": + let iter = db.queryIter(prefix = "k", skip = 1) + check: + not iter.finished + iter.next() == (k2, v2) + not iter.finished + iter.next() == empty + iter.finished + + test "iterate only 'k', limit": + let iter = db.queryIter(prefix = "k", limit = 1) + check: + not iter.finished + iter.next() == (k1, v1) + not iter.finished + iter.next() == empty + iter.finished + test "iterates only 'k', only keys": let iter = db.queryIter(prefix = "k", keysOnly = true) check: