/
db_repo.go
61 lines (48 loc) · 1.13 KB
/
db_repo.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
package car
import (
"gorm.io/gorm"
"github.com/dentonliu/go-clean-starter/internal/entity"
)
func NewDBRepo(db *gorm.DB) Repo {
return &dbRepo{db}
}
type dbRepo struct {
db *gorm.DB
}
func (r *dbRepo) Get(id uint) (entity.Car, error) {
var model entity.Car
res := r.db.Limit(1).Find(&model, id)
return model, res.Error
}
func (r *dbRepo) Create(model *entity.Car) error {
res := r.db.Create(model)
return res.Error
}
func (r *dbRepo) Update(model *entity.Car, attrs ...string) error {
tx := r.db.Model(model)
if len(attrs) <= 0 {
tx.Omit("ID")
} else {
tx.Select(attrs)
}
res := tx.Updates(*model)
return res.Error
}
func (r *dbRepo) Save(model *entity.Car) error {
res := r.db.Save(model)
return res.Error
}
func (r *dbRepo) Delete(model *entity.Car) error {
res := r.db.Delete(model)
return res.Error
}
func (r *dbRepo) Count() (int, error) {
var count int64
res := r.db.Model(&entity.Car{}).Count(&count)
return int(count), res.Error
}
func (r *dbRepo) Query(offset, limit int) ([]entity.Car, error) {
models := []entity.Car{}
res := r.db.Offset(offset).Limit(limit).Find(&models)
return models, res.Error
}