Add tryGet<RecordName> versions of get<Record> calls
`tryGet<RecordName>` returns Option types rather than raise exceptions. For example: generateProcsForModels(MyDb, [ User ]) will now create both: proc getUser*(db: MyDb, id: string): User proc tryGetUser*(db: MyDb, id: string): Option[User]
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# Package
|
||||
|
||||
version = "4.0.0"
|
||||
version = "4.1.0"
|
||||
author = "Jonathan Bernard"
|
||||
description = "Lightweight Postgres ORM for Nim."
|
||||
license = "GPL-3.0"
|
||||
|
@@ -334,7 +334,6 @@ proc createRecord*[D: DbConnType, T](db: D, rec: T): T =
|
||||
" RETURNING " & columnNamesForModel(rec).join(",")
|
||||
|
||||
logQuery("createRecord", sqlStmt)
|
||||
debug(getLogger("query"), %*{ "values": mc.values })
|
||||
|
||||
let newRow = db.getRow(sql(sqlStmt), mc.values)
|
||||
|
||||
@@ -403,6 +402,19 @@ template getRecord*[D: DbConnType](db: D, modelType: type, id: typed): untyped =
|
||||
|
||||
rowToModel(modelType, row)
|
||||
|
||||
template tryGetRecord*[D: DbConnType](db: D, modelType: type, id: typed): untyped =
|
||||
## Fetch a record by id.
|
||||
let sqlStmt =
|
||||
"SELECT " & columnNamesForModel(modelType).join(",") &
|
||||
" FROM " & tableName(modelType) &
|
||||
" WHERE id = ?"
|
||||
|
||||
logQuery("tryGetRecord", sqlStmt, [("id", $id)])
|
||||
let row = db.getRow(sql(sqlStmt), @[$id])
|
||||
|
||||
if allIt(row, it.len == 0): none[modelType]()
|
||||
else: some(rowToModel(modelType, row))
|
||||
|
||||
template findRecordsWhere*[D: DbConnType](
|
||||
db: D,
|
||||
modelType: type,
|
||||
@@ -603,6 +615,7 @@ macro generateProcsForModels*(dbType: type, modelTypes: openarray[type]): untype
|
||||
|
||||
let modelName = $(t.getType[1])
|
||||
let getName = ident("get" & modelName)
|
||||
let tryGetName = ident("tryGet" & modelName)
|
||||
let getIfExistsName = ident("get" & modelName & "IfItExists")
|
||||
let getAllName = ident("getAll" & pluralize(modelName))
|
||||
let findWhereName = ident("find" & pluralize(modelName) & "Where")
|
||||
@@ -615,6 +628,9 @@ macro generateProcsForModels*(dbType: type, modelTypes: openarray[type]): untype
|
||||
proc `getName`*(db: `dbType`, id: `idType`): `t` =
|
||||
db.withConnection conn: result = getRecord(conn, `t`, id)
|
||||
|
||||
proc `tryGetName`*(db: `dbType`, id: `idType`): Option[`t`] =
|
||||
db.withConnection conn: result = tryGetRecord(conn, `t`, id)
|
||||
|
||||
proc `getIfExistsName`*(db: `dbType`, id: `idType`): Option[`t`] =
|
||||
db.withConnection conn:
|
||||
try: result = some(getRecord(conn, `t`, id))
|
||||
|
Reference in New Issue
Block a user