-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
48 lines (43 loc) · 1.02 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package opinionatedsagas
import (
"context"
"database/sql"
"reflect"
)
func isInterface[T any](t reflect.Type) bool {
return t.Implements(reflect.TypeOf((*T)(nil)).Elem())
}
func sqlWithTx[R any](db *sql.DB, do func(tx *sql.Tx) (R, error)) (R, error) {
var zero R
tx, err := db.Begin()
defer tx.Rollback() //nolint the error is not relevant
if err != nil {
return zero, err
}
r, err := do(tx)
if err != nil {
return zero, err
}
if err := tx.Commit(); err != nil {
return zero, err
}
return r, nil
}
func sqlCreate(ctx context.Context, tx *sql.Tx, query string, args ...any) (int64, error) {
row := tx.QueryRowContext(ctx, query, args...)
var id int64
if err := row.Scan(&id); err != nil {
return 0, err
}
return id, nil
}
func sqlFindOne[R any](
ctx context.Context, tx *sql.Tx, query string, fields func(item *R) []any, args ...any,
) (R, error) {
row := tx.QueryRowContext(ctx, query, args...)
var item, zero R
if err := row.Scan(fields(&item)...); err != nil {
return zero, err
}
return item, nil
}