sdbc/update_scope.go

72 lines
1.6 KiB
Go

package sdbc
import (
"context"
"gitter.top/common/goref"
)
type _update struct {
scope *scope
sdbc *Driver
ctx context.Context
where []any
selectOpts []interface{}
omitOpts []string
}
// SetWhere 设置更新条件
func (u *_update) SetWhere(query any, args ...any) *_update {
u.where = append(u.where, query)
u.where = append(u.where, args...)
return u
}
// SetSelect 只更新字段 对Updates有效
func (u *_update) SetSelect(selects ...any) *_update {
u.selectOpts = selects
return u
}
// SetOmit 忽略字段 对Updates有效
func (u *_update) SetOmit(omits ...string) *_update {
u.omitOpts = omits
return u
}
// Replace 更新保存所有的字段,即使字段是零值
func (u *_update) Replace(doc any) error {
// 不是结构体 返回错误
if !goref.IsBaseStruct(doc) {
return ErrorUnavailableType
}
db := u.sdbc.client
if len(u.where) != 0 {
db = db.Where(u.where[0], u.where[1:]...)
}
return db.Save(doc).Error
}
// Update 更新单个字段
func (u *_update) Update(column string, value any) error {
db := u.sdbc.client
if len(u.where) != 0 {
db = db.Where(u.where[0], u.where[1:]...)
}
return db.Model(u.scope.model.ptr()).Update(column, value).Error
}
// Updates 更新多个字段
func (u *_update) Updates(m map[string]interface{}) error {
db := u.sdbc.client
if len(u.where) != 0 {
db = db.Where(u.where[0], u.where[1:]...)
}
if len(u.selectOpts) != 0 {
db = db.Select(u.selectOpts[0], u.selectOpts[1:]...)
}
if len(u.omitOpts) != 0 {
db = db.Omit(u.omitOpts...)
}
return db.Model(u.scope.model.ptr()).Updates(m).Error
}