-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm_repository.go
79 lines (60 loc) · 1.62 KB
/
gorm_repository.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
package repositories
import (
"strings"
"github.com/KejawenLab/bima/v4/configs"
"github.com/KejawenLab/bima/v4/models"
"gorm.io/gorm"
)
type GormRepository struct {
pool *gorm.DB
model string
}
func (r *GormRepository) Model(model string) {
r.model = model
}
func (r *GormRepository) Transaction(f Transaction) error {
r.pool = configs.Database
configs.Database = configs.Database.Begin()
result := f(r)
if result != nil {
configs.Database.Rollback()
configs.Database = r.pool
return result
}
configs.Database.Commit()
configs.Database = r.pool
return result
}
func (r *GormRepository) Create(v interface{}) error {
return configs.Database.Create(v).Error
}
func (r *GormRepository) Update(v interface{}) error {
return configs.Database.Save(v).Error
}
func (r *GormRepository) Bind(v interface{}, id string) error {
return configs.Database.Where("id = ?", id).First(v).Error
}
func (r *GormRepository) All(v interface{}) error {
return configs.Database.Find(v).Error
}
func (r *GormRepository) FindBy(v interface{}, filters ...Filter) error {
db := configs.Database
var filter strings.Builder
for _, f := range filters {
filter.Reset()
filter.WriteString(f.Field)
filter.WriteString(" ")
filter.WriteString(f.Operator)
filter.WriteString(" ?")
db = db.Where(filter.String(), f.Value)
}
return db.Find(v).Error
}
func (r *GormRepository) Delete(v interface{}, id string) error {
m := v.(models.GormModel)
if m.IsSoftDelete() {
configs.Database.Save(v)
return configs.Database.Where("id = ?", id).Delete(v).Error
}
return configs.Database.Unscoped().Where("id = ?", id).Delete(v).Error
}