From f54bf6e9747eea89fec25129f3a7d7391f42f041 Mon Sep 17 00:00:00 2001 From: Jonathan Bernard Date: Tue, 2 Sep 2025 00:35:54 -0500 Subject: [PATCH] Add tryGet versions of get calls `tryGet` 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] --- fiber_orm.nimble | 2 +- src/fiber_orm.nim | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/fiber_orm.nimble b/fiber_orm.nimble index 3b52251..cbe2710 100644 --- a/fiber_orm.nimble +++ b/fiber_orm.nimble @@ -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" diff --git a/src/fiber_orm.nim b/src/fiber_orm.nim index 549ad14..b0d524c 100644 --- a/src/fiber_orm.nim +++ b/src/fiber_orm.nim @@ -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))