Skip to content

Commit

Permalink
[perf] 优化自增id增长过快的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
runs committed Jan 2, 2023
1 parent d623624 commit d5f5a21
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions internal/repository/bilbil_video.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,18 +132,26 @@ func (impl *BilibiliVideoMysqlImpl) Shield(bvid string) error {

func (impl *BilibiliVideoMysqlImpl) Save(e *idl.BilibiliVideo) error {
return impl.tx.Transaction(func(_tx *gorm.DB) error {
result := _tx.Table(bilibiliVideoTableName).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "bvid"}},
DoUpdates: clause.AssignmentColumns(strings.Split(onUpdateFields, ",")),
}).Create(&e)

result := _tx.Table(bilibiliVideoTableName).Where("bvid = ?", e.Bvid).Select("id").Find(&e.Id)
if result.Error != nil {
return errors.Wrap(result.Error, fmt.Sprintf("insert %s fail", bilibiliVideoTableName))
return errors.Wrap(result.Error, fmt.Sprintf("select %s fail bvid: %s", bilibiliVideoTableName, e.Bvid))
}

// on update
if e.Id == 0 {
_tx.Table(bilibiliVideoTableName).Where("bvid = ?", e.Bvid).Select("id").Find(&e.Id)
// on create
if e.Id != 0 {
result = _tx.Table(bilibiliVideoTableName).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "bvid"}},
DoUpdates: clause.AssignmentColumns(strings.Split(onUpdateFields, ",")),
}).Create(&e)

if result.Error != nil {
return errors.Wrap(result.Error, fmt.Sprintf("insert %s fail", bilibiliVideoTableName))
}
} else {
result = _tx.Table(bilibiliVideoTableName).Where("bvid = ?", e.Bvid).Updates(e)
if result.Error != nil {
return errors.Wrap(result.Error, fmt.Sprintf("update %s fail", bilibiliVideoTableName))
}
}

tags := strings.Split(e.Tag, ",")
Expand Down

0 comments on commit d5f5a21

Please sign in to comment.