@@ -44,6 +44,20 @@ func QueryValue[T any](ctx context.Context, query string, args ...any) (value T,
44
44
return value , nil
45
45
}
46
46
47
+ // QueryValueReplaceErrNoRows queries a single value of type T.
48
+ // In case of an sql.ErrNoRows error, errNoRows will be called
49
+ // and its result returned together with the default value for T.
50
+ func QueryValueReplaceErrNoRows [T any ](ctx context.Context , errNoRows func () error , query string , args ... any ) (value T , err error ) {
51
+ err = Conn (ctx ).QueryRow (query , args ... ).Scan (& value )
52
+ if err != nil {
53
+ if errors .Is (err , sql .ErrNoRows ) && errNoRows != nil {
54
+ return * new (T ), errNoRows ()
55
+ }
56
+ return * new (T ), err
57
+ }
58
+ return value , nil
59
+ }
60
+
47
61
// QueryValueOr queries a single value of type T
48
62
// or returns the passed defaultValue in case of sql.ErrNoRows.
49
63
func QueryValueOr [T any ](ctx context.Context , defaultValue T , query string , args ... any ) (value T , err error ) {
@@ -66,6 +80,20 @@ func QueryRowStruct[S any](ctx context.Context, query string, args ...any) (row
66
80
return row , nil
67
81
}
68
82
83
+ // QueryRowStructReplaceErrNoRows queries a row and scans it as struct.
84
+ // In case of an sql.ErrNoRows error, errNoRows will be called
85
+ // and its result returned as error together with nil as row.
86
+ func QueryRowStructReplaceErrNoRows [S any ](ctx context.Context , errNoRows func () error , query string , args ... any ) (row * S , err error ) {
87
+ err = Conn (ctx ).QueryRow (query , args ... ).ScanStruct (& row )
88
+ if err != nil {
89
+ if errors .Is (err , sql .ErrNoRows ) && errNoRows != nil {
90
+ return nil , errNoRows ()
91
+ }
92
+ return nil , err
93
+ }
94
+ return row , nil
95
+ }
96
+
69
97
// QueryRowStructOrNil queries a row and scans it as struct
70
98
// or returns nil in case of sql.ErrNoRows.
71
99
func QueryRowStructOrNil [S any ](ctx context.Context , query string , args ... any ) (row * S , err error ) {
0 commit comments