Skip to content

Commit f9c6f3d

Browse files
authored
Merge pull request #6 from mildred/implement-option-column-type
Add missing conversion for Option[T] types
2 parents 2f14a0b + a96615e commit f9c6f3d

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/easy_sqlite3/bindings.nim

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,12 @@ proc `[]=`*(st: ref Statement, idx: int, val: type(nil)) =
491491
proc `[]=`*(st: ref Statement, idx: int, val: string) =
492492
st.raw.sqliteCheck sqlite3_bind_text(st.raw, idx, val, int32 val.len, TransientDestructor)
493493
494+
proc `[]=`*[T](st: ref Statement, idx: int, val: Option[T]) =
495+
if val.is_none:
496+
st.raw.sqliteCheck sqlite3_bind_null(st.raw, idx)
497+
else:
498+
st[idx] = val.get
499+
494500
proc reset*(st: ref Statement) =
495501
st.raw.sqliteCheck sqlite3_reset(st.raw)
496502
@@ -534,7 +540,7 @@ proc getColumn*[T](st: ref Statement, idx: int, _: typedesc[Option[T]]): Option[
534540
if st.getColumnType(idx) == dt_null:
535541
none(T)
536542
else:
537-
st.getColumn(idx, T)
543+
some(st.getColumn(idx, T))
538544
539545
proc unpack*[T: tuple](st: ref Statement, _: typedesc[T]): T =
540546
var idx = 0

tests/test_option.nim

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import std/unittest
2+
import std/options
3+
4+
import easy_sqlite3
5+
6+
proc returnOptionNone(): tuple[col: Option[int]] {.importdb: "SELECT NULL;".}
7+
proc returnOptionSome(): tuple[col: Option[int]] {.importdb: "SELECT 1;".}
8+
9+
proc takeOption(col: Option[int]): tuple[val: int, is_null: bool] {.importdb: "SELECT COALESCE($col, 0), $col IS NULL".}
10+
11+
iterator options(a: Option[int], b: Option[int], c: Option[int]): tuple[val: Option[int]] {.importdb: "VALUES ($a+1), ($b+1), ($c+1)".} = discard
12+
13+
suite "option":
14+
setup:
15+
var db = initDatabase(":memory:")
16+
17+
test "return option none":
18+
let col = db.returnOptionNone().col
19+
check col.is_none()
20+
21+
test "return option some":
22+
let col = db.returnOptionSome().col
23+
check col.is_some()
24+
check col.get == 1
25+
26+
test "take option none":
27+
let res = db.takeOption(none(int))
28+
check res.is_null
29+
check res.val == 0
30+
31+
test "take option some":
32+
let res = db.takeOption(some(1))
33+
check not res.is_null
34+
check res.val == 1
35+
36+
test "iterator options":
37+
var res: seq[Option[int]] = @[]
38+
for row in db.options(some(1), none(int), some(2)):
39+
res.add(row.val)
40+
check res == @[some(2), none(int), some(3)]

0 commit comments

Comments
 (0)