-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm.go
68 lines (57 loc) · 1.36 KB
/
gorm.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
package txngorm
import (
"context"
"github.com/9ssi7/txn"
"gorm.io/gorm"
)
// GAdapter is the interface for interacting with GORM within a transaction.
// It extends the txn.Adapter interface to provide additional GORM-specific functionality.
type GAdapter interface {
txn.Adapter
// GetCurrent returns the current *gorm.DB instance to use for executing GORM operations.
// Depending on the transaction state, this may be the original db instance or a transaction object.
GetCurrent(ctx context.Context) *gorm.DB
}
// New creates a new GAdapter instance using the provided *gorm.DB.
func New(db *gorm.DB) GAdapter {
return &gormAdapter{db: db}
}
type gormAdapter struct {
db *gorm.DB
tx *gorm.DB
}
func (a *gormAdapter) Begin(ctx context.Context) error {
tx := a.db.WithContext(ctx).Begin()
if tx.Error != nil {
return tx.Error
}
a.tx = tx
return nil
}
func (a *gormAdapter) Commit(_ context.Context) error {
if a.tx == nil {
return nil
}
err := a.tx.Commit().Error
a.tx = nil
return err
}
func (a *gormAdapter) Rollback(_ context.Context) error {
if a.tx == nil {
return nil
}
err := a.tx.Rollback().Error
a.tx = nil
return err
}
func (a *gormAdapter) End(_ context.Context) {
if a.tx != nil {
a.tx = nil
}
}
func (a *gormAdapter) GetCurrent(ctx context.Context) *gorm.DB {
if a.tx != nil {
return a.tx
}
return a.db.WithContext(ctx)
}