/
relationNum.go
461 lines (403 loc) · 12.9 KB
/
relationNum.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package dao
import (
"context"
"errors"
"fmt"
"time"
"community/internal/cache"
"community/internal/model"
cacheBase "github.com/zhufuyi/sponge/pkg/cache"
"github.com/zhufuyi/sponge/pkg/mysql/query"
"github.com/zhufuyi/sponge/pkg/utils"
"golang.org/x/sync/singleflight"
"gorm.io/gorm"
)
var _ RelationNumDao = (*relationNumDao)(nil)
// RelationNumDao defining the dao interface
type RelationNumDao interface {
Create(ctx context.Context, table *model.RelationNum) error
DeleteByID(ctx context.Context, id uint64) error
DeleteByIDs(ctx context.Context, ids []uint64) error
UpdateByID(ctx context.Context, table *model.RelationNum) error
GetByID(ctx context.Context, id uint64) (*model.RelationNum, error)
GetByCondition(ctx context.Context, condition *query.Conditions) (*model.RelationNum, error)
GetByIDs(ctx context.Context, ids []uint64) (map[uint64]*model.RelationNum, error)
GetByColumns(ctx context.Context, params *query.Params) ([]*model.RelationNum, int64, error)
ModifyFollowingNumByTx(ctx context.Context, tx *gorm.DB, userID uint64, num int) error
ModifyFollowerNumByTx(ctx context.Context, tx *gorm.DB, followedUid uint64, num int) error
CreateByTx(ctx context.Context, tx *gorm.DB, table *model.RelationNum) (uint64, error)
DeleteByTx(ctx context.Context, tx *gorm.DB, id uint64) error
UpdateByTx(ctx context.Context, tx *gorm.DB, table *model.RelationNum) error
}
type relationNumDao struct {
db *gorm.DB
cache cache.RelationNumCache
sfg *singleflight.Group
}
// NewRelationNumDao creating the dao interface
func NewRelationNumDao(db *gorm.DB, xCache cache.RelationNumCache) RelationNumDao {
return &relationNumDao{
db: db,
cache: xCache,
sfg: new(singleflight.Group),
}
}
// Create a record, insert the record and the id value is written back to the table
func (d *relationNumDao) Create(ctx context.Context, table *model.RelationNum) error {
err := d.db.WithContext(ctx).Create(table).Error
_ = d.cache.Del(ctx, table.ID)
return err
}
// DeleteByID delete a record by id
func (d *relationNumDao) DeleteByID(ctx context.Context, id uint64) error {
err := d.db.WithContext(ctx).Where("id = ?", id).Delete(&model.RelationNum{}).Error
if err != nil {
return err
}
// delete cache
_ = d.cache.Del(ctx, id)
return nil
}
// DeleteByIDs delete records by batch id
func (d *relationNumDao) DeleteByIDs(ctx context.Context, ids []uint64) error {
err := d.db.WithContext(ctx).Where("id IN (?)", ids).Delete(&model.RelationNum{}).Error
if err != nil {
return err
}
// delete cache
for _, id := range ids {
_ = d.cache.Del(ctx, id)
}
return nil
}
// UpdateByID update a record by id
func (d *relationNumDao) UpdateByID(ctx context.Context, table *model.RelationNum) error {
err := d.updateDataByID(ctx, d.db, table)
// delete cache
_ = d.cache.Del(ctx, table.ID)
return err
}
func (d *relationNumDao) updateDataByID(ctx context.Context, db *gorm.DB, table *model.RelationNum) error {
if table.ID < 1 {
return errors.New("id cannot be 0")
}
update := map[string]interface{}{}
if table.UserID != 0 {
update["user_id"] = table.UserID
}
if table.FollowingNum != 0 {
update["following_num"] = table.FollowingNum
}
if table.FollowerNum != 0 {
update["follower_num"] = table.FollowerNum
}
return db.WithContext(ctx).Model(table).Updates(update).Error
}
// GetByID get a record by id
func (d *relationNumDao) GetByID(ctx context.Context, id uint64) (*model.RelationNum, error) {
record, err := d.cache.Get(ctx, id)
if err == nil {
return record, nil
}
if errors.Is(err, model.ErrCacheNotFound) {
// for the same id, prevent high concurrent simultaneous access to mysql
val, err, _ := d.sfg.Do(utils.Uint64ToStr(id), func() (interface{}, error) { //nolint
table := &model.RelationNum{}
err = d.db.WithContext(ctx).Where("id = ?", id).First(table).Error
if err != nil {
// if data is empty, set not found cache to prevent cache penetration, default expiration time 10 minutes
if errors.Is(err, model.ErrRecordNotFound) {
err = d.cache.SetCacheWithNotFound(ctx, id)
if err != nil {
return nil, err
}
return nil, model.ErrRecordNotFound
}
return nil, err
}
// set cache
err = d.cache.Set(ctx, id, table, cache.RelationNumExpireTime)
if err != nil {
return nil, fmt.Errorf("cache.Set error: %v, id=%d", err, id)
}
return table, nil
})
if err != nil {
return nil, err
}
table, ok := val.(*model.RelationNum)
if !ok {
return nil, model.ErrRecordNotFound
}
return table, nil
} else if errors.Is(err, cacheBase.ErrPlaceholder) {
return nil, model.ErrRecordNotFound
}
// fail fast, if cache error return, don't request to db
return nil, err
}
// GetByCondition get a record by condition
// query conditions:
//
// name: column name
// exp: expressions, which default is "=", support =, !=, >, >=, <, <=, like, in
// value: column value, if exp=in, multiple values are separated by commas
// logic: logical type, defaults to and when value is null, only &(and), ||(or)
//
// example: find a male aged 20
//
// condition = &query.Conditions{
// Columns: []query.Column{
// {
// Name: "age",
// Value: 20,
// },
// {
// Name: "gender",
// Value: "male",
// },
// }
func (d *relationNumDao) GetByCondition(ctx context.Context, c *query.Conditions) (*model.RelationNum, error) {
queryStr, args, err := c.ConvertToGorm()
if err != nil {
return nil, err
}
table := &model.RelationNum{}
err = d.db.WithContext(ctx).Where(queryStr, args...).First(table).Error
if err != nil {
return nil, err
}
return table, nil
}
// GetByIDs list of records by batch id
func (d *relationNumDao) GetByIDs(ctx context.Context, ids []uint64) (map[uint64]*model.RelationNum, error) {
itemMap, err := d.cache.MultiGet(ctx, ids)
if err != nil {
return nil, err
}
var missedIDs []uint64
for _, id := range ids {
_, ok := itemMap[id]
if !ok {
missedIDs = append(missedIDs, id)
continue
}
}
// get missed data
if len(missedIDs) > 0 {
// find the id of an active placeholder, i.e. an id that does not exist in mysql
var realMissedIDs []uint64
for _, id := range missedIDs {
_, err = d.cache.Get(ctx, id)
if errors.Is(err, cacheBase.ErrPlaceholder) {
continue
}
realMissedIDs = append(realMissedIDs, id)
}
if len(realMissedIDs) > 0 {
var missedData []*model.RelationNum
err = d.db.WithContext(ctx).Where("id IN (?)", realMissedIDs).Find(&missedData).Error
if err != nil {
return nil, err
}
if len(missedData) > 0 {
for _, data := range missedData {
itemMap[data.ID] = data
}
err = d.cache.MultiSet(ctx, missedData, cache.RelationNumExpireTime)
if err != nil {
return nil, err
}
} else {
for _, id := range realMissedIDs {
_ = d.cache.SetCacheWithNotFound(ctx, id)
}
}
}
}
return itemMap, nil
}
// GetByColumns get records by paging and column information,
// Note: query performance degrades when table rows are very large because of the use of offset.
//
// params includes paging parameters and query parameters
// paging parameters (required):
//
// page: page number, starting from 0
// size: lines per page
// sort: sort fields, default is id backwards, you can add - sign before the field to indicate reverse order, no - sign to indicate ascending order, multiple fields separated by comma
//
// query parameters (not required):
//
// name: column name
// exp: expressions, which default is "=", support =, !=, >, >=, <, <=, like, in
// value: column value, if exp=in, multiple values are separated by commas
// logic: logical type, defaults to and when value is null, only &(and), ||(or)
//
// example: search for a male over 20 years of age
//
// params = &query.Params{
// Page: 0,
// Size: 20,
// Columns: []query.Column{
// {
// Name: "age",
// Exp: ">",
// Value: 20,
// },
// {
// Name: "gender",
// Value: "male",
// },
// }
func (d *relationNumDao) GetByColumns(ctx context.Context, params *query.Params) ([]*model.RelationNum, int64, error) {
queryStr, args, err := params.ConvertToGormConditions()
if err != nil {
return nil, 0, errors.New("query params error: " + err.Error())
}
var total int64
if params.Sort != "ignore count" { // determine if count is required
err = d.db.WithContext(ctx).Model(&model.RelationNum{}).Select([]string{"id"}).Where(queryStr, args...).Count(&total).Error
if err != nil {
return nil, 0, err
}
if total == 0 {
return nil, total, nil
}
}
records := []*model.RelationNum{}
order, limit, offset := params.ConvertToPage()
err = d.db.WithContext(ctx).Order(order).Limit(limit).Offset(offset).Where(queryStr, args...).Find(&records).Error
if err != nil {
return nil, 0, err
}
return records, total, err
}
// CreateByTx create a record in the database using the provided transaction
func (d *relationNumDao) CreateByTx(ctx context.Context, tx *gorm.DB, table *model.RelationNum) (uint64, error) {
err := tx.WithContext(ctx).Create(table).Error
return table.ID, err
}
// DeleteByTx delete a record by id in the database using the provided transaction
func (d *relationNumDao) DeleteByTx(ctx context.Context, tx *gorm.DB, id uint64) error {
update := map[string]interface{}{
"deleted_at": time.Now(),
}
err := tx.WithContext(ctx).Model(&model.RelationNum{}).Where("id = ?", id).Updates(update).Error
if err != nil {
return err
}
// delete cache
_ = d.cache.Del(ctx, id)
return nil
}
// UpdateByTx update a record by id in the database using the provided transaction
func (d *relationNumDao) UpdateByTx(ctx context.Context, tx *gorm.DB, table *model.RelationNum) error {
err := d.updateDataByID(ctx, tx, table)
// delete cache
_ = d.cache.Del(ctx, table.ID)
return err
}
// GetByUserID get a record based on user id
func (d *relationNumDao) GetByUserID(ctx context.Context, userID uint64) (*model.RelationNum, error) {
record, err := d.cache.GetByUid(ctx, userID)
if err == nil {
return record, nil
}
if errors.Is(err, model.ErrCacheNotFound) {
// for the same id, prevent high concurrent simultaneous access to mysql
val, err, _ := d.sfg.Do("relationNum:"+utils.Uint64ToStr(userID), func() (interface{}, error) { //nolint
table := &model.RelationNum{}
err = d.db.WithContext(ctx).Where("user_id = ?", userID).First(table).Error
if err != nil {
// if data is empty, set not found cache to prevent cache penetration, default expiration time 10 minutes
if errors.Is(err, model.ErrRecordNotFound) {
err = d.cache.SetByUidCacheWithNotFound(ctx, userID)
if err != nil {
return nil, err
}
return nil, model.ErrRecordNotFound
}
return nil, err
}
// set cache
err = d.cache.SetByUid(ctx, userID, table, cache.RelationNumExpireTime)
if err != nil {
return nil, fmt.Errorf("cache.Set error: %v, id=%d", err, userID)
}
return table, nil
})
if err != nil {
return nil, err
}
table, ok := val.(*model.RelationNum)
if !ok {
return nil, model.ErrRecordNotFound
}
return table, nil
} else if errors.Is(err, cacheBase.ErrPlaceholder) {
return nil, model.ErrRecordNotFound
}
// fail fast, if cache error return, don't request to db
return nil, err
}
// ModifyFollowingNumByTx 添加或减少关注数, num=1 is added, num=-1 is subtraction
func (d *relationNumDao) ModifyFollowingNumByTx(ctx context.Context, tx *gorm.DB, userID uint64, num int) error {
table := &model.RelationNum{}
err := tx.WithContext(ctx).Where("user_id = ?", userID).First(table).Error
if err != nil && !errors.Is(err, model.ErrRecordNotFound) {
return err
}
if num > 0 { // 增加关注数
if table.ID == 0 {
table.UserID = userID
table.FollowingNum = 1
return tx.WithContext(ctx).Create(table).Error
}
table.FollowingNum += 1
} else { // 减少关注数
if table.ID == 0 {
table.UserID = userID
table.FollowingNum = 0
return tx.WithContext(ctx).Create(table).Error
}
table.FollowingNum -= 1
if table.FollowingNum < 0 {
table.FollowingNum = 0
}
}
update := map[string]interface{}{
"following_num": table.FollowingNum,
}
return tx.WithContext(ctx).Model(table).Updates(update).Error
}
// ModifyFollowerNumByTx 添加或减少粉丝数, num=1 is added, num=-1 is subtraction
func (d *relationNumDao) ModifyFollowerNumByTx(ctx context.Context, tx *gorm.DB, followedUid uint64, num int) error {
table := &model.RelationNum{}
err := tx.WithContext(ctx).Where("user_id = ?", followedUid).First(table).Error
if err != nil && !errors.Is(err, model.ErrRecordNotFound) {
return err
}
if num > 0 { // 增加粉丝数
if table.ID == 0 {
table.UserID = followedUid
table.FollowerNum = 1
return tx.WithContext(ctx).Create(table).Error
}
table.FollowerNum += 1
} else { // 减少粉丝数
if table.ID == 0 {
table.UserID = followedUid
table.FollowerNum = 0
return tx.WithContext(ctx).Create(table).Error
}
table.FollowerNum -= 1
if table.FollowerNum < 0 {
table.FollowerNum = 0
}
}
update := map[string]interface{}{
"follower_num": table.FollowerNum,
}
return tx.WithContext(ctx).Model(table).Updates(update).Error
}