nim-datastore/datastore/sql/sqliteds.nim

224 lines
5.8 KiB
Nim
Raw Normal View History

2022-09-16 21:14:31 -06:00
import std/times
import std/options
2022-09-16 21:14:31 -06:00
import pkg/questionable
import pkg/questionable/results
import pkg/sqlite3_abi
from pkg/stew/results as stewResults import isErr
import pkg/upraises
2023-09-20 17:49:57 -07:00
import ../backend
2022-09-16 21:14:31 -06:00
import ./sqlitedsdb
2023-09-20 17:49:57 -07:00
export backend, sqlitedsdb
2022-09-16 21:14:31 -06:00
push: {.upraises: [].}
type
2023-09-20 17:12:19 -07:00
SQLiteDatastore* = object
2023-03-09 10:24:44 +01:00
db: SQLiteDsDb
2022-09-16 21:14:31 -06:00
proc path*(self: SQLiteDatastore): string =
self.db.dbPath
2023-09-20 17:12:19 -07:00
proc readOnly*(self: SQLiteDatastore): bool = self.db.readOnly
2022-09-16 21:14:31 -06:00
proc timestamp*(t = epochTime()): int64 =
(t * 1_000_000).int64
2023-09-20 20:26:34 -07:00
proc has*(self: SQLiteDatastore, key: DbKey): ?!bool =
2022-09-16 21:14:31 -06:00
var
exists = false
2023-09-20 20:04:44 -07:00
key = $key
2022-09-16 21:14:31 -06:00
proc onData(s: RawStmtPtr) =
exists = sqlite3_column_int64(s, ContainsStmtExistsCol.cint).bool
2023-09-20 20:04:44 -07:00
if err =? self.db.containsStmt.query((key), onData).errorOption:
2022-12-02 16:25:44 -06:00
return failure err
2022-09-16 21:14:31 -06:00
return success exists
2023-09-20 17:49:57 -07:00
proc delete*(self: SQLiteDatastore, key: DbKey): ?!void =
return self.db.deleteStmt.exec((key.data))
2022-09-16 21:14:31 -06:00
2023-09-20 21:21:15 -07:00
proc delete*(self: SQLiteDatastore, keys: openArray[DbKey]): ?!void =
if err =? self.db.beginStmt.exec().errorOption:
return failure(err)
for key in keys:
if err =? self.db.deleteStmt.exec((key.id)).errorOption:
if err =? self.db.rollbackStmt.exec().errorOption:
return failure err.msg
return failure err.msg
if err =? self.db.endStmt.exec().errorOption:
return failure err.msg
return success()
2023-09-20 17:49:57 -07:00
proc get*(self: SQLiteDatastore, key: DbKey): ?!seq[byte] =
2022-09-16 21:14:31 -06:00
# see comment in ./filesystem_datastore re: finer control of memory
2023-09-20 17:12:19 -07:00
# allocation in `proc get`, could apply here as well if bytes were read
2022-09-16 21:14:31 -06:00
# incrementally with `sqlite3_blob_read`
var
bytes: seq[byte]
proc onData(s: RawStmtPtr) =
2022-09-19 17:29:32 -06:00
bytes = self.db.getDataCol()
2022-09-16 21:14:31 -06:00
2023-09-20 22:12:53 -07:00
if err =? self.db.getStmt.query((key), onData).errorOption:
return failure(err)
if bytes.len <= 0:
return failure(
2023-09-20 17:49:57 -07:00
newException(DatastoreKeyNotFound, "DbKey doesn't exist"))
2022-09-16 21:14:31 -06:00
return success bytes
2023-09-20 21:21:15 -07:00
proc put*(self: SQLiteDatastore, key: DbKey, data: DbVal): ?!void =
when DbVal is seq[byte]:
2023-09-20 22:12:53 -07:00
return self.db.putStmt.exec((key, data, timestamp()))
2023-09-20 21:21:15 -07:00
elif DbVal is DataBuffer:
return self.db.putBufferStmt.exec((key.id, data, timestamp()))
else:
{.error: "unknown type".}
2022-09-16 21:14:31 -06:00
2023-09-20 21:21:15 -07:00
proc put*(self: SQLiteDatastore, batch: openArray[DbBatchEntry]): ?!void =
if err =? self.db.beginStmt.exec().errorOption:
return failure err
for entry in batch:
if err =? self.db.putStmt.exec((entry.key.id, entry.data, timestamp())).errorOption:
if err =? self.db.rollbackStmt.exec().errorOption:
return failure err
return failure err
if err =? self.db.endStmt.exec().errorOption:
return failure err
return success()
2023-09-20 17:12:19 -07:00
proc close*(self: SQLiteDatastore): ?!void =
2022-09-19 22:40:01 -06:00
self.db.close()
2022-09-19 22:40:01 -06:00
return success()
2023-09-20 20:57:47 -07:00
proc query*(self: SQLiteDatastore,
query: DbQuery
): Result[iterator(): ?!DbQueryResponse {.closure.}, ref CatchableError] =
var
queryStr = if query.value:
QueryStmtDataIdStr
else:
QueryStmtIdStr
if query.sort == SortOrder.Descending:
queryStr &= QueryStmtOrderDescending
else:
queryStr &= QueryStmtOrderAscending
if query.limit != 0:
queryStr &= QueryStmtLimit
if query.offset != 0:
queryStr &= QueryStmtOffset
let
queryStmt = QueryStmt.prepare(
self.db.env, queryStr).expect("should not fail")
s = RawStmtPtr(queryStmt)
var
v = sqlite3_bind_text(
2023-09-20 20:57:47 -07:00
s, 1.cint, ($query.key & "*").cstring, -1.cint, SQLITE_TRANSIENT_GCSAFE)
if not (v == SQLITE_OK):
return failure newException(DatastoreError, $sqlite3_errstr(v))
if query.limit != 0:
v = sqlite3_bind_int(s, 2.cint, query.limit.cint)
if not (v == SQLITE_OK):
return failure newException(DatastoreError, $sqlite3_errstr(v))
if query.offset != 0:
v = sqlite3_bind_int(s, 3.cint, query.offset.cint)
if not (v == SQLITE_OK):
return failure newException(DatastoreError, $sqlite3_errstr(v))
2023-09-20 20:59:06 -07:00
success iterator(): ?!DbQueryResponse {.closure.} =
2023-09-14 18:34:20 -06:00
2023-09-20 20:57:47 -07:00
try:
let
v = sqlite3_step(s)
2023-09-14 18:34:20 -06:00
2023-09-20 20:57:47 -07:00
case v
of SQLITE_ROW:
let
key = KeyId.new(sqlite3_column_text_not_null(s, QueryStmtIdCol))
2023-09-14 18:34:20 -06:00
2023-09-20 20:57:47 -07:00
blob: ?pointer =
if query.value: sqlite3_column_blob(s, QueryStmtDataCol).some
else: pointer.none
2023-09-20 20:57:47 -07:00
# detect out-of-memory error
# see the conversion table and final paragraph of:
# https://www.sqlite.org/c3ref/column_blob.html
# see also https://www.sqlite.org/rescode.html
2023-09-20 20:57:47 -07:00
# the "data" column can be NULL so in order to detect an out-of-memory
# error it is necessary to check that the result is a null pointer and
# that the result code is an error code
if blob.isSome and blob.get().isNil:
let v = sqlite3_errcode(sqlite3_db_handle(s))
2023-09-20 20:57:47 -07:00
if not (v in [SQLITE_OK, SQLITE_ROW, SQLITE_DONE]):
return failure newException(DatastoreError, $sqlite3_errstr(v))
2023-09-20 20:57:47 -07:00
let
dataLen = sqlite3_column_bytes(s, QueryStmtDataCol)
data =
if blob.isSome: DataBuffer.new(blob.get(), 0, dataLen - 1)
else: DataBuffer.new(0)
return success (key.some, data)
of SQLITE_DONE:
2023-09-20 21:21:15 -07:00
return
2023-09-20 20:57:47 -07:00
else:
return failure newException(DatastoreError, $sqlite3_errstr(v))
2023-09-20 20:57:47 -07:00
finally:
discard sqlite3_reset(s)
discard sqlite3_clear_bindings(s)
s.dispose()
return
2023-09-20 22:12:53 -07:00
proc contains*(self: SQLiteDatastore, key: DbKey): bool =
return self.has(key)
2022-09-16 21:14:31 -06:00
2023-09-20 17:12:19 -07:00
proc new*(T: type SQLiteDatastore,
path: string,
readOnly = false): ?!T =
2022-09-16 21:14:31 -06:00
let
flags =
if readOnly: SQLITE_OPEN_READONLY
else: SQLITE_OPEN_READWRITE or SQLITE_OPEN_CREATE
2023-09-20 17:12:19 -07:00
success SQLiteDatastore(db: ? SQLiteDsDb.open(path, flags))
2022-09-16 21:14:31 -06:00
2023-09-20 17:12:19 -07:00
proc new*(T: type SQLiteDatastore,
db: SQLiteDsDb): ?!T =
2022-09-16 21:14:31 -06:00
2023-09-20 17:12:19 -07:00
success SQLiteDatastore(db: db)