-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
74 lines (61 loc) · 1.68 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package database
import (
"context"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/teablog/tea/internal/db"
"gorm.io/gorm"
)
type _session struct{}
var Session = &_session{}
const (
DbSessionAppointTag = "__session_appoint__"
DbSessionRuntimeTag = "__session_runtime__"
DbSessionRuntimeDefaultTag = "default"
)
func (*_session) StartToContext(ctx context.Context) context.Context {
if ginCtx, ok := ctx.(*gin.Context); ok {
ginCtx.Set(DbSessionRuntimeTag, db.DB.Session(&gorm.Session{}))
return ginCtx
} else {
return context.WithValue(ctx, DbSessionRuntimeTag, db.DB.Session(&gorm.Session{}))
}
}
func (s *_session) Close(ctx context.Context) {
sess, _ := s.getRuntimeFromContext(ctx)
if sess != nil {
sess.Commit()
}
}
func (*_session) getRuntimeFromContext(ctx context.Context) (*gorm.DB, error) {
ri := ctx.Value(DbSessionRuntimeTag)
if ri == nil {
return nil, errors.New("getRuntimeFromContext fail: session runtime not found in context")
}
r, ok := ri.(*gorm.DB)
if !ok {
return nil, errors.New("getRuntimeFromContext fail: not is sessionRuntime")
}
return r, nil
}
func (*_session) getConnection(ctx context.Context) string {
conn := DbSessionRuntimeDefaultTag
connFromContext := ctx.Value(DbSessionAppointTag)
if connFromContext != nil {
appointConn := connFromContext.(string)
if appointConn != "" {
conn = appointConn
}
}
return conn
}
func (*_session) getFromContext(ctx context.Context) (*gorm.DB, error) {
r, err := Session.getRuntimeFromContext(ctx)
if err != nil {
return nil, err
}
return r, nil
}
func (s *_session) GetFromContext(ctx context.Context) (*gorm.DB, error) {
return s.getFromContext(ctx)
}