From 3514ee6484038b7e66540f5b5853831198562412 Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Thu, 27 May 2021 11:31:34 +0200 Subject: [PATCH] sqlite: quick exec with result (#361) --- eth/db/kvstore_sqlite3.nim | 10 ++++++++++ tests/db/test_kvstore_sqlite3.nim | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/eth/db/kvstore_sqlite3.nim b/eth/db/kvstore_sqlite3.nim index 0e63904..87089a6 100644 --- a/eth/db/kvstore_sqlite3.nim +++ b/eth/db/kvstore_sqlite3.nim @@ -226,6 +226,16 @@ proc exec*[Params: tuple](db: SqStoreRef, if finalizeStatus != SQLITE_OK and result.isOk: return err($sqlite3_errstr(finalizeStatus)) +proc exec*[Params: tuple, Res](db: SqStoreRef, + stmt: string, + params: Params, + onData: ResultHandler[Res]): KvResult[bool] = + let stmt = ? db.prepareStmt(stmt, Params, Res, managed = false) + result = exec(stmt, params, onData) + let finalizeStatus = sqlite3_finalize(RawStmtPtr stmt) + if finalizeStatus != SQLITE_OK and result.isOk: + return err($sqlite3_errstr(finalizeStatus)) + template exec*(db: SqStoreRef, stmt: string): KvResult[void] = exec(db, stmt, ()) diff --git a/tests/db/test_kvstore_sqlite3.nim b/tests/db/test_kvstore_sqlite3.nim index 9694f2f..0f49ff3 100644 --- a/tests/db/test_kvstore_sqlite3.nim +++ b/tests/db/test_kvstore_sqlite3.nim @@ -52,6 +52,15 @@ procSuite "SqStoreRef": countRes.isOk and countRes.get == true totalRecords == 3 + # Without prepare.. + totalRecords = 0 + check: + (db.exec("SELECT COUNT(*) FROM records;", ()) do (res: int64): + totalRecords = int res).get() + + check: + totalRecords == 3 + let selectRangeStmt = db.prepareStmt( "SELECT value FROM records WHERE key >= ? and key < ?;", (int64, int64), openarray[byte]).get