pg_users_repository.go
7.5 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/cache"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/constant"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/transform"
)
type UserRepository struct {
*cache.CachedRepository
transactionContext *pgTransaction.TransactionContext
}
func (repository *UserRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
sqlBuildFields := []string{
"user_id",
"company_id",
"user_base_id",
"user_type",
"user_code",
"organization_id",
"department_id",
"user_org",
"user_role",
"favorite_menus",
"cooperation_info",
"enable_status",
"ext",
"created_at",
"updated_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if user.Identify() == nil {
//userId, err := repository.nextIdentify()
//if err != nil {
// return user, err
//} else {
// user.UserId = userId
//}
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.CompanyId,
&user.UserBaseId,
&user.UserType,
&user.UserCode,
&user.OrganizationId,
&user.DepartmentId,
&user.UserOrg,
&user.UserRole,
&user.FavoriteMenus,
&user.CooperationInfo,
&user.EnableStatus,
&user.Ext,
&user.CreatedAt,
&user.UpdatedAt,
),
fmt.Sprintf("INSERT INTO users.\"user\" (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
//user.UserId,
user.CompanyId,
user.UserBaseId,
user.UserType,
user.UserCode,
user.OrganizationId,
user.DepartmentId,
user.UserOrg,
user.UserRole,
user.FavoriteMenus,
user.CooperationInfo,
user.EnableStatus,
user.Ext,
user.CreatedAt,
user.UpdatedAt,
); err != nil {
return user, err
}
} else {
queryFunc := func() (interface{}, error) {
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.CompanyId,
&user.UserBaseId,
&user.UserType,
&user.UserCode,
&user.OrganizationId,
&user.DepartmentId,
&user.UserOrg,
&user.UserRole,
&user.FavoriteMenus,
&user.CooperationInfo,
&user.EnableStatus,
&user.Ext,
&user.CreatedAt,
&user.UpdatedAt,
),
fmt.Sprintf(`UPDATE users."user" SET %s WHERE user_id=? RETURNING %s`, updateFieldsSnippet, returningFieldsSnippet),
user.CompanyId,
user.UserBaseId,
user.UserType,
user.UserCode,
user.OrganizationId,
user.DepartmentId,
user.UserOrg,
user.UserRole,
user.FavoriteMenus,
user.CooperationInfo,
user.EnableStatus,
user.Ext,
user.CreatedAt,
user.UpdatedAt,
user.Identify(),
); err != nil {
return user, err
}
return user, nil
}
if _, err := repository.Query(queryFunc, user.CacheKeyFunc()); err != nil {
return user, err
}
}
return user, nil
}
func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
userModel.UserId = user.Identify().(int64)
queryFunc := func() (interface{}, error) {
if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
return user, err
}
return user, nil
}
if _, err := repository.Query(queryFunc, user.CacheKeyFunc()); err != nil {
return user, err
}
return user, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
queryFunc := func() (interface{}, error) {
query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
query.SetWhereByQueryOption("user_id = ?", "userId")
query.SetWhereByQueryOption("company_id=?", "companyId")
query.SetWhereByQueryOption("organization_id=?", "organizationId")
query.SetWhereByQueryOption("user_base_id=?", "userBaseId")
query.SetWhereByQueryOption("user_code = ?", "userCode")
query.SetWhereByQueryOption("user_id != ?", "notEqualUserId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
return userModel, nil
}
var cacheModel = &domain.User{}
if _, ok := queryOptions["userId"]; ok {
cacheModel.UserId = queryOptions["userId"].(int64)
}
if err := repository.QueryCache(cacheModel.CacheKeyFunc, userModel, queryFunc, cache.WithObjectToExpire(constant.REPOSITORY_CACHE_EXPIRE)); err != nil {
return nil, err
}
if userModel.UserId == 0 {
return nil, nil
} else {
return transform.TransformToUserDomainModelFromPgModels(userModel)
}
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
tx := repository.transactionContext.PgTx
var userModels []*models.User
users := make([]*domain.User, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
query.SetWhereByQueryOption("company_id=?", "companyId")
query.SetWhereByQueryOption("organization_id=?", "organizationId")
if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int64)) > 0 {
query.Where(`organization_id in (?)`, pg.In(v))
}
query.SetWhereByQueryOption("user_base_id=?", "userBaseId")
query.SetWhereByQueryOption("(user_type & ?)>0", "userType")
query.SetWhereByQueryOption("enable_status=?", "enableStatus")
query.SetWhereByQueryOption(fmt.Sprintf(`user_role @> '[{"roleId":%v}]'`, queryOptions["roleId"]), "roleId")
if v, ok := queryOptions["depName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'depName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'userName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["cooperationCompany"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`cooperation_info->>'cooperationCompany' like '%%%v%%'`, v))
}
query.SetOffsetAndLimit(20)
query.SetOrderDirect("user_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, users, err
} else {
for _, userModel := range userModels {
if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
return 0, users, err
} else {
users = append(users, user)
}
}
return int64(count), users, nil
}
}
func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &UserRepository{
transactionContext: transactionContext,
CachedRepository: cache.NewDefaultCachedRepository(),
}, nil
}
}