-
Notifications
You must be signed in to change notification settings - Fork 8
/
handler.go
53 lines (45 loc) · 1.46 KB
/
handler.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
49
50
51
52
53
package juice
import (
"context"
"database/sql"
)
// QueryHandler defines the handler of the query.
type QueryHandler func(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// ExecHandler defines the handler of the exec.
type ExecHandler func(ctx context.Context, query string, args ...any) (sql.Result, error)
func sessionQueryHandler() QueryHandler {
return func(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
sess := SessionFromContext(ctx)
if sess == nil {
return nil, ErrNoSession
}
return sess.QueryContext(ctx, query, args...)
}
}
func sessionExecHandler() ExecHandler {
return func(ctx context.Context, query string, args ...any) (sql.Result, error) {
sess := SessionFromContext(ctx)
if sess == nil {
return nil, ErrNoSession
}
return sess.ExecContext(ctx, query, args...)
}
}
// GenericQueryHandler defines the handler of the generic query.
type GenericQueryHandler[T any] func(ctx context.Context, query string, args ...any) (T, error)
func CombineQueryHandler(stmt Statement, middlewares ...Middleware) QueryHandler {
next := sessionQueryHandler()
if len(middlewares) > 0 {
group := MiddlewareGroup(middlewares)
return group.QueryContext(stmt, next)
}
return next
}
func CombineExecHandler(stmt Statement, middlewares ...Middleware) ExecHandler {
next := sessionExecHandler()
if len(middlewares) > 0 {
group := MiddlewareGroup(middlewares)
return group.ExecContext(stmt, next)
}
return next
}