-
Notifications
You must be signed in to change notification settings - Fork 8
/
session.go
30 lines (24 loc) · 889 Bytes
/
session.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
package juice
import (
"context"
"database/sql"
"errors"
)
// Session is a wrapper of sql.DB and sql.Tx
type Session interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}
// ErrNoSession is the error that no session found in context.
var ErrNoSession = errors.New("no session found in context")
type sessionKey struct{}
// SessionWithContext returns a new context with the session.
func SessionWithContext(ctx context.Context, sess Session) context.Context {
return context.WithValue(ctx, sessionKey{}, sess)
}
// SessionFromContext returns the session from the context.
func SessionFromContext(ctx context.Context) Session {
sess, _ := ctx.Value(sessionKey{}).(Session)
return sess
}