pg_task_repository.go
2.6 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package repository
import (
"errors"
"fmt"
"time"
"github.com/go-pg/pg/v10"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
)
//任务
type TaskRepository struct {
transactionContext *pgTransaction.TransactionContext
}
var _ domain.TaskRepository = (*TaskRepository)(nil)
func (repo *TaskRepository) TransformToDomain(d *models.Task) *domain.Task {
return &domain.Task{
Id: d.Id,
CreatedAt: d.CreatedAt,
UpdatedAt: d.UpdatedAt,
DeletedAt: d.DeletedAt,
Name: d.Name,
Leader: d.Leader,
Status: domain.TaskState(d.Status),
Level: d.Level,
LevalName: d.LevalName,
}
}
func (repo *TaskRepository) Save(param *domain.Task) error {
param.UpdatedAt = time.Now()
if param.Id == 0 {
param.CreatedAt = time.Now()
return nil
}
m := models.Task{
Id: param.Id,
CreatedAt: param.CreatedAt,
UpdatedAt: param.UpdatedAt,
DeletedAt: param.DeletedAt,
Name: param.Name,
Leader: param.Leader,
Status: int(param.Status),
Level: param.Level,
LevalName: param.LevalName,
}
db := repo.transactionContext.PgTx
if m.Id == 0 {
_, err := db.Model(&m).Insert()
if err != nil {
return err
}
} else {
_, err := db.Model(&m).WherePK().Update()
if err != nil {
return err
}
}
param.Id = m.Id
return nil
}
func (repo *TaskRepository) Remove(id int) error {
tx := repo.transactionContext.PgTx
nowTime := time.Now()
_, err := tx.Model(&models.Task{}).
Where("id=?", id).
Set("deleted_at=?", nowTime).
Update()
return err
}
func (repo *TaskRepository) FindOne(queryOptions map[string]interface{}) (*domain.Task, error) {
tx := repo.transactionContext.PgTx
m := new(models.Task)
query := tx.Model(m)
query.Where("deleted_at isnull")
if id, ok := queryOptions["id"]; ok {
query.Where("id=?", id)
}
if err := query.First(); err != nil {
if errors.Is(err, pg.ErrNoRows) {
return nil, fmt.Errorf("没有找到task数据")
} else {
return nil, err
}
}
u := repo.TransformToDomain(m)
return u, nil
}
func (repo *TaskRepository) Find(queryOptions map[string]interface{}) (int, []*domain.Task, error) {
tx := repo.transactionContext.PgTx
var m []*models.Task
query := tx.Model(&m).
Where("deleted_at isnull").
Limit(20)
query.Order("id desc")
count, err := query.SelectAndCount()
if err != nil {
return 0, nil, err
}
var datas []*domain.Task
for _, v := range m {
d := repo.TransformToDomain(v)
datas = append(datas, d)
}
return count, datas, nil
}