From fe37a82d0495a8b59b80677dd42d0d94ffafdfb4 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Thu, 17 Sep 2026 15:50:45 +0200 Subject: gsql: add NoneIfNoRows --- gsql/gsql.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'gsql/gsql.go') diff --git a/gsql/gsql.go b/gsql/gsql.go index 7df830c..e7e2aa3 100644 --- a/gsql/gsql.go +++ b/gsql/gsql.go @@ -14,6 +14,9 @@ package gsql import ( "context" "database/sql" + "errors" + + . "go.xyrillian.de/gg/option" ) // ConnectionHandle extends [Handle] with methods that make sense for handles referring to entire connections or connection pools, but not e.g. to transactions. @@ -76,3 +79,18 @@ type Rows interface { Next() bool Scan(slots ...any) error } + +// NoneIfNoRows wraps any call returning a record from a DB that may return [sql.ErrNoRows], +// and converts that error into a [None] in the value position instead. +// +// [None]: https://pkg.go.dev/go.xyrillian.de/gg/option#None +func NoneIfNoRows[T any](value T, err error) (Option[T], error) { + switch { + case err == nil: + return Some(value), nil + case errors.Is(err, sql.ErrNoRows): + return None[T](), nil + default: + return None[T](), err + } +} -- cgit v1.3.1