Skip to content

Commit cf43903

Browse files
committed
Implement sqlToTypeAs
1 parent 3811112 commit cf43903

3 files changed

Lines changed: 38 additions & 2 deletions

File tree

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,21 @@ ____
547547

548548
The `totypes` module contains procs to convert the result to types.
549549

550+
```nim
551+
type
552+
Person = ref object
553+
id: int
554+
username: string
555+
age: int
556+
secretIdent: string
557+
is_nimmer: bool
558+
559+
let
560+
columns = @["name AS username","id","ident AS secretIdent"]
561+
val = db.getRow(sql("SELECT " & columns.join(",") & " FROM my_table WHERE id = 1"))
562+
res = sqlToTypeAs(Person, columns, val)
563+
```
564+
550565
```nim
551566
type
552567
Person = ref object

sqlbuilder.nimble

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Package
22

3-
version = "1.1.1"
3+
version = "1.1.2"
44
author = "ThomasTJdev"
55
description = "SQL builder"
66
license = "MIT"

src/sqlbuilderpkg/totypes.nim

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,25 @@ proc sqlToType*[T](t: typedesc[T], columns, val: seq[string]): T =
6363
proc sqlToType*[T](t: typedesc[T], columns: seq[string], vals: seq[seq[string]]): seq[T] =
6464
for v in vals:
6565
result.add(sqlToType(t, columns, v))
66-
return result
66+
return result
67+
68+
69+
proc sqlToTypeAs*[T](t: typedesc[T], columns, val: seq[string]): T =
70+
let tmp = t()
71+
72+
for fieldName, field in tmp[].fieldPairs:
73+
var
74+
found = false
75+
for ci in 0..columns.high:
76+
let cSplit = columns[ci].toLowerAscii().split(" as ")
77+
if cSplit.len() == 2:
78+
if cSplit[1].strip() == fieldName:
79+
parseVal(val[ci], field)
80+
found = true
81+
break
82+
if not found:
83+
parseVal(field)
84+
else:
85+
found = false
86+
87+
return tmp

0 commit comments

Comments
 (0)