-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
103 lines (88 loc) · 2.02 KB
/
db.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package db
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
)
//go:generate go run gen/cmd/gen.go
type DB struct {
// Collections _ connected collections from model
Users *UserModel
}
type Options struct {
Client *mongo.Client
DB string // db name to connect
}
// ConnectAll -- connect to mongo tables
func Connect(opt Options) *DB {
clientDB := opt.Client.Database(opt.DB)
return &DB{
Users: &UserModel{
collection: clientDB.Collection("users"),
},
}
}
// MongoTransaction -
type MongoTransaction struct {
context context.Context
Cancel context.CancelFunc
Session mongo.Session
SessionContext mongo.SessionContext
err error
}
// EndSession -
func (t *MongoTransaction) EndSession() {
defer t.Cancel()
defer t.Session.EndSession(t.context)
}
// AbortTransaction -
func (t *MongoTransaction) AbortTransaction() error {
err := t.Session.AbortTransaction(t.SessionContext)
defer t.EndSession()
return err
}
// CommitTransaction -
func (t *MongoTransaction) CommitTransaction() error {
err := t.Session.CommitTransaction(t.SessionContext)
defer t.EndSession()
return err
}
// SetError -
func (t *MongoTransaction) SetErr(err error) {
t.err = err
}
// CommitOrAbort -
func (t *MongoTransaction) CommitOrAbort() error {
if t.err != nil {
return t.AbortTransaction()
}
return t.CommitTransaction()
}
// NewTransaction - Start mongo transaction
func NewTransaction(client *mongo.Client) (*MongoTransaction, error) {
t := &MongoTransaction{}
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
t.Cancel = cancel
t.context = ctx
session, err := client.StartSession()
if err != nil {
cancel()
return nil, err
}
if err = session.StartTransaction(); err != nil {
cancel()
session.EndSession(ctx)
return nil, err
}
t.Session = session
err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
t.SessionContext = sc
return nil
})
if err != nil {
cancel()
session.EndSession(ctx)
return nil, err
}
return t, nil
}