go-gorm / optimisticlock

optimistic lock plugin for gorm
MIT License
88 stars 16 forks source link

无法执行乐观锁 #36

Closed kuangshp closed 3 months ago

kuangshp commented 3 months ago
for i := 0; i < 10; i++ {
        go func(i int) {
            info, _ := dao.UserEntity.WithContext(ctx).Where(dao.UserEntity.ID.Eq(1)).Updates(&model.UserEntity{
                Avatar: "12",
            })
            if info.RowsAffected == 1 {
                fmt.Println("更新成功", i)
            } else {
                fmt.Println("更新失败", i)
            }
        }(i)
    }

运行后的sql

UPDATE `user` SET `avatar`='12',`version`=`version`+1,`updated_at`='2024-07-14 21:19:59.649' WHERE `user`.`id` = 1 AND `user`.`deleted_at` IS NULL

根据mysql乐观锁执行来说,先查询当前的version=?,在更新的时候加上这个条件去更新数据,但是我使用这个插件的时候没有

icpd commented 3 months ago

使用Model方法传入一个带有当前version值的user对象

---原始邮件--- 发件人: @.> 发送时间: 2024年7月14日(周日) 晚上9:21 收件人: @.>; 抄送: @.***>; 主题: [go-gorm/optimisticlock] 无法执行热关锁 (Issue #36)

for i := 0; i < 10; i++ { go func(i int) { info, _ := dao.UserEntity.WithContext(ctx).Where(dao.UserEntity.ID.Eq(1)).Updates(&model.UserEntity{ Avatar: "12", }) if info.RowsAffected == 1 { fmt.Println("更新成功", i) } else { fmt.Println("更新失败", i) } }(i) }

运行后的sql UPDATE user SET avatar='12',version=version+1,updated_at='2024-07-14 21:19:59.649' WHERE user.id = 1 AND user.deleted_at IS NULL

根据mysql乐观锁执行来说,先查询当前的version=?,在更新的时候加上这个条件去更新数据,但是我使用这个插件的时候没有

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you are subscribed to this thread.Message ID: @.***>

kuangshp commented 3 months ago

有的, image

type Version = optimisticlock.Version

我看gorm-gen来更新只能是手动加这个条件上去的,

userEntity, _ := dao.UserEntity.WithContext(ctx).Where(dao.UserEntity.ID.Eq(1)).First()
            info, _ := dao.UserEntity.WithContext(ctx).Where(
                dao.UserEntity.ID.Eq(1),
                dao.UserEntity.Version.Eq(userEntity.Version),
            ).Updates(&model.UserEntity{
                Avatar: "12",
            })
            if info.RowsAffected == 1 {
                fmt.Println("更新成功", i)
            } else {
                fmt.Println("更新失败", i)
            }

不知道有没有更优的方案

djx30103 commented 3 months ago
do := dao.UserEntity.WithContext(ctx)
do.ReplaceDB(do.UnderlyingDB().Model(userEntity))

info, _ := do.Where(dao.UserEntity.ID.Eq(1)).Updates(&model.UserEntity{
    Password: "12",
})
if info.RowsAffected == 1 {
    fmt.Println("更新成功")
} else {
    fmt.Println("更新失败")
}