mdbc/update.go

105 lines
2.3 KiB
Go

package mdbc
import (
"context"
"fmt"
"gitter.top/common/goref"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type updateScope struct {
scope *scope
mdbc *mdbc
ctx context.Context
filter any
docs any
opts any
err error
}
func (us *updateScope) SetContext(ctx context.Context) *updateScope {
us.ctx = ctx
return us
}
func (us *updateScope) SetUpdateOptions(opts options.UpdateOptions) *updateScope {
us.opts = &opts
return us
}
func (us *updateScope) SetReplaceOptions(opts options.ReplaceOptions) *updateScope {
us.opts = &opts
return us
}
func (us *updateScope) SetID(id ...any) *updateScope {
if len(id) == 0 {
return us
}
if len(id) == 1 {
us.filter = bson.M{
"_id": id[0],
}
}
if len(id) > 1 {
us.filter = bson.M{
"_id": bson.M{"$in": id},
}
}
return us
}
func (us *updateScope) SetFilter(filter interface{}) *updateScope {
if us.filter != nil {
return us
}
if filter == nil {
us.filter = bson.M{}
return us
}
if goref.IsBaseStruct(filter) || goref.IsBaseMap(filter) {
us.filter = filter
return us
}
us.err = fmt.Errorf("filter type must be struct or map")
return us
}
func (us *updateScope) mergeOptions() {
if us.ctx == nil {
us.ctx = context.Background()
}
if us.filter == nil {
us.filter = bson.M{}
}
if us.opts == nil {
us.opts = new(options.UpdateOptions)
}
if goref.IsBaseStruct(us.docs) {
us.docs = bson.M{"$set": us.docs}
}
if goref.IsBaseMap(us.docs) && !goref.ExistMapKey(us.docs, "$set") {
us.docs = bson.M{"$set": us.docs}
}
}
func (us *updateScope) One(docs interface{}) (*mongo.UpdateResult, error) {
us.docs = docs
us.mergeOptions()
return us.mdbc.database.Collection(us.scope.tableName).UpdateOne(us.ctx, us.filter, us.docs, us.opts.(*options.UpdateOptions))
}
func (us *updateScope) Many(docs interface{}) (*mongo.UpdateResult, error) {
us.docs = docs
us.mergeOptions()
return us.mdbc.database.Collection(us.scope.tableName).UpdateMany(us.ctx, us.filter, us.docs, us.opts.(*options.UpdateOptions))
}
func (us *updateScope) Replace(docs interface{}) (*mongo.UpdateResult, error) {
us.docs = docs
us.mergeOptions()
return us.mdbc.database.Collection(us.scope.tableName).ReplaceOne(us.ctx, us.filter, us.docs, us.opts.(*options.ReplaceOptions))
}