/
m_user.go
331 lines (278 loc) · 9.17 KB
/
m_user.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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package mysql
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/LyricTian/gin-admin/src/model"
"github.com/LyricTian/gin-admin/src/schema"
"github.com/LyricTian/gin-admin/src/service/mysql"
"github.com/facebookgo/inject"
"github.com/pkg/errors"
)
// User 用户管理
type User struct {
DB *mysql.DB
Common *Common
}
// Init 初始化
func (a *User) Init(g *inject.Graph, db *mysql.DB, c *Common) *User {
a.DB = db
a.Common = c
g.Provide(&inject.Object{Value: model.IUser(a), Name: "IUser"})
db.CreateTableIfNotExists(schema.User{}, a.TableName())
db.CreateTableIfNotExists(schema.UserRole{}, a.UserRoleTableName())
db.CreateTableIndex(a.TableName(), "idx_record_id", true, "record_id")
db.CreateTableIndex(a.TableName(), "idx_user_name", false, "user_name")
db.CreateTableIndex(a.TableName(), "idx_real_name", false, "real_name")
db.CreateTableIndex(a.TableName(), "idx_status", false, "status")
db.CreateTableIndex(a.TableName(), "idx_deleted", false, "deleted")
db.CreateTableIndex(a.UserRoleTableName(), "idx_user_id", false, "user_id")
db.CreateTableIndex(a.UserRoleTableName(), "idx_deleted", false, "deleted")
return a
}
// TableName 表名
func (a *User) TableName() string {
return a.Common.TableName("user")
}
// UserRoleTableName 用户角色表名
func (a *User) UserRoleTableName() string {
return a.Common.TableName("user_role")
}
// QueryPage 查询分页数据
func (a *User) QueryPage(ctx context.Context, params schema.UserQueryParam, pageIndex, pageSize uint) (int64, []*schema.UserQueryResult, error) {
var (
where = "WHERE deleted=0"
args []interface{}
)
if params.UserName != "" {
where = fmt.Sprintf("%s AND user_name LIKE ?", where)
args = append(args, "%"+params.UserName+"%")
}
if params.RealName != "" {
where = fmt.Sprintf("%s AND real_name LIKE ?", where)
args = append(args, "%"+params.RealName+"%")
}
if params.Status != 0 {
where = fmt.Sprintf("%s AND status = ?", where)
args = append(args, params.Status)
}
if params.RoleID != "" {
where = fmt.Sprintf("%s AND record_id IN(SELECT user_id FROM %s WHERE deleted=0 AND role_id=?)", where, a.UserRoleTableName())
args = append(args, params.RoleID)
}
count, err := a.DB.SelectInt(fmt.Sprintf("SELECT COUNT(*) FROM %s %s", a.TableName(), where), args...)
if err != nil {
return 0, nil, errors.Wrap(err, "查询分页数据发生错误")
} else if count == 0 {
return 0, nil, nil
}
var items []*schema.UserQueryResult
fields := "id,record_id,user_name,real_name,status,created"
_, err = a.DB.Select(&items, fmt.Sprintf("SELECT %s FROM %s %s ORDER BY id DESC LIMIT %d,%d", fields, a.TableName(), where, (pageIndex-1)*pageSize, pageSize), args...)
if err != nil {
return 0, nil, errors.Wrap(err, "查询分页数据发生错误")
}
return count, items, nil
}
// Get 查询指定数据
func (a *User) Get(ctx context.Context, recordID string, includeRoleIDs bool) (*schema.User, error) {
var item schema.User
fields := "id,record_id,user_name,real_name,password,status,creator,created,deleted"
err := a.DB.SelectOne(&item, fmt.Sprintf("SELECT %s FROM %s WHERE deleted=0 AND record_id=?", fields, a.TableName()), recordID)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "查询指定数据发生错误")
}
if includeRoleIDs {
roleIDs, err := a.QueryRoleIDs(ctx, item.RecordID)
if err != nil {
return nil, err
}
item.RoleIDs = roleIDs
}
return &item, nil
}
// Check 检查数据是否存在
func (a *User) Check(ctx context.Context, recordID string) (bool, error) {
n, err := a.DB.SelectInt(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE deleted=0 AND record_id=?", a.TableName()), recordID)
if err != nil {
return false, errors.Wrap(err, "检查数据是否存在发生错误")
}
return n > 0, nil
}
// QueryRoleIDs 查询用户角色
func (a *User) QueryRoleIDs(ctx context.Context, userID string) ([]string, error) {
query := fmt.Sprintf("SELECT role_id FROM %s WHERE deleted=0 AND user_id=?", a.UserRoleTableName())
var items []*schema.UserRole
_, err := a.DB.Select(&items, query, userID)
if err != nil {
return nil, errors.Wrap(err, "查询用户角色发生错误")
}
roleIDs := make([]string, len(items))
for i, item := range items {
roleIDs[i] = item.RoleID
}
return roleIDs, nil
}
// CheckUserName 检查用户名
func (a *User) CheckUserName(ctx context.Context, userName string) (bool, error) {
query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE deleted=0 AND user_name=?", a.TableName())
n, err := a.DB.SelectInt(query, userName)
if err != nil {
return false, errors.Wrap(err, "检查用户名发生错误")
}
return n > 0, nil
}
// GetByUserName 根据用户名查询指定数据
func (a *User) GetByUserName(ctx context.Context, userName string, includeRoleIDs bool) (*schema.User, error) {
var item schema.User
fields := "id,record_id,user_name,real_name,password,status,creator,created,deleted"
err := a.DB.SelectOne(&item, fmt.Sprintf("SELECT %s FROM %s WHERE deleted=0 AND user_name=?", fields, a.TableName()), userName)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.Wrap(err, "根据用户名查询指定数据发生错误")
}
if includeRoleIDs {
roleIDs, err := a.QueryRoleIDs(ctx, item.RecordID)
if err != nil {
return nil, err
}
item.RoleIDs = roleIDs
}
return &item, nil
}
// CheckByRoleID 检查角色下是否存在用户
func (a *User) CheckByRoleID(ctx context.Context, roleID string) (bool, error) {
n, err := a.DB.SelectInt(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE deleted=0 AND role_id=?", a.UserRoleTableName()), roleID)
if err != nil {
return false, errors.Wrap(err, "检查角色下是否存在用户发生错误")
}
return n > 0, nil
}
// QueryUserRoles 查询用户角色
func (a *User) QueryUserRoles(ctx context.Context, params schema.UserRoleQueryParam) ([]*schema.UserRole, error) {
var (
where = "WHERE deleted=0"
args []interface{}
)
if params.UserID != "" {
where = fmt.Sprintf("%s AND user_id=?", where)
args = append(args, params.UserID)
}
var items []*schema.UserRole
query := fmt.Sprintf("SELECT user_id,role_id FROM %s %s", a.UserRoleTableName(), where)
_, err := a.DB.Select(&items, query, args...)
if err != nil {
return nil, errors.Wrap(err, "查询用户角色发生错误")
}
return items, nil
}
// Create 创建数据
func (a *User) Create(ctx context.Context, item *schema.User) error {
tran, err := a.DB.Begin()
if err != nil {
return errors.Wrap(err, "创建数据发生错误")
}
err = tran.Insert(item)
if err != nil {
tran.Rollback()
return errors.Wrap(err, "创建数据发生错误")
}
for _, roleID := range item.RoleIDs {
userRoleItem := &schema.UserRole{
UserID: item.RecordID,
RoleID: roleID,
}
err = tran.Insert(userRoleItem)
if err != nil {
tran.Rollback()
return errors.Wrap(err, "创建数据发生错误")
}
}
err = tran.Commit()
if err != nil {
return errors.Wrap(err, "创建数据发生错误")
}
return nil
}
// Update 更新数据
func (a *User) Update(ctx context.Context, recordID string, info map[string]interface{}) error {
if _, ok := info["updated"]; !ok {
info["updated"] = time.Now().Unix()
}
_, err := a.DB.UpdateByPK(a.TableName(),
map[string]interface{}{"record_id": recordID},
info)
if err != nil {
return errors.Wrap(err, "更新数据发生错误")
}
return nil
}
// UpdateWithRoleIDs 更新数据
func (a *User) UpdateWithRoleIDs(ctx context.Context, recordID string, info map[string]interface{}, roleIDs []string) error {
tran, err := a.DB.Begin()
if err != nil {
return errors.Wrap(err, "更新数据发生错误")
}
_, err = a.DB.UpdateByPKWithTran(tran, a.TableName(),
map[string]interface{}{"record_id": recordID},
info)
if err != nil {
tran.Rollback()
return errors.Wrap(err, "更新数据发生错误")
}
_, err = a.DB.UpdateByPKWithTran(tran, a.UserRoleTableName(),
map[string]interface{}{"user_id": recordID},
map[string]interface{}{"deleted": time.Now().Unix()})
if err != nil {
tran.Rollback()
return errors.Wrap(err, "更新数据发生错误")
}
for _, roleID := range roleIDs {
userRoleItem := &schema.UserRole{
UserID: recordID,
RoleID: roleID,
}
err = tran.Insert(userRoleItem)
if err != nil {
tran.Rollback()
return errors.Wrap(err, "创建数据发生错误")
}
}
err = tran.Commit()
if err != nil {
return errors.Wrap(err, "更新数据发生错误")
}
return nil
}
// Delete 删除数据
func (a *User) Delete(ctx context.Context, recordID string) error {
tran, err := a.DB.Begin()
if err != nil {
return errors.Wrap(err, "删除数据发生错误")
}
_, err = a.DB.UpdateByPKWithTran(tran, a.TableName(),
map[string]interface{}{"record_id": recordID},
map[string]interface{}{"deleted": time.Now().Unix()})
if err != nil {
tran.Rollback()
return errors.Wrap(err, "删除数据发生错误")
}
_, err = a.DB.UpdateByPKWithTran(tran, a.UserRoleTableName(),
map[string]interface{}{"user_id": recordID},
map[string]interface{}{"deleted": time.Now().Unix()})
if err != nil {
tran.Rollback()
return errors.Wrap(err, "删除数据发生错误")
}
err = tran.Commit()
if err != nil {
return errors.Wrap(err, "删除数据发生错误")
}
return nil
}