mdbc/drop_scope.go
2022-02-23 16:59:45 +08:00

111 lines
1.9 KiB
Go

package mdbc
import (
"context"
"errors"
"time"
"go.mongodb.org/mongo-driver/mongo"
)
type DropScope struct {
scope *Scope
cw *ctxWrap
err error
}
// SetContext 设置上下文
func (ds *DropScope) SetContext(ctx context.Context) *DropScope {
if ds.cw == nil {
ds.cw = &ctxWrap{}
}
ds.cw.ctx = ctx
return ds
}
func (ds *DropScope) preCheck() {
var breakerTTL time.Duration
if ds.scope.breaker == nil {
breakerTTL = defaultBreakerTime
} else if ds.scope.breaker.ttl == 0 {
breakerTTL = defaultBreakerTime
} else {
breakerTTL = ds.scope.breaker.ttl
}
if ds.cw == nil {
ds.cw = &ctxWrap{}
}
if ds.cw.ctx == nil {
ds.cw.ctx, ds.cw.cancel = context.WithTimeout(context.Background(), breakerTTL)
}
}
func (ds *DropScope) assertErr() {
if ds.err == nil {
return
}
if errors.Is(ds.err, context.DeadlineExceeded) {
ds.err = &ErrRequestBroken
return
}
err, ok := ds.err.(mongo.CommandError)
if !ok {
return
}
if err.HasErrorMessage(context.DeadlineExceeded.Error()) {
ds.err = &ErrRequestBroken
return
}
}
func (ds *DropScope) doString() string {
return "drop()"
}
func (ds *DropScope) debug() {
if !ds.scope.debug {
return
}
debugger := &Debugger{
collection: ds.scope.tableName,
execT: ds.scope.execT,
action: ds,
}
debugger.String()
}
func (ds *DropScope) getContext() context.Context {
return ds.cw.ctx
}
func (ds *DropScope) doClear() {
if ds.cw != nil && ds.cw.cancel != nil {
ds.cw.cancel()
}
ds.scope.execT = 0
ds.scope.debug = false
}
// Do 删除Model绑定的集合
func (ds *DropScope) Do() error {
defer ds.doClear()
ds.preCheck()
defer ds.assertErr()
var starTime time.Time
if ds.scope.debug {
starTime = time.Now()
}
ds.err = db.Collection(ds.scope.tableName).Drop(ds.getContext())
if ds.scope.debug {
ds.scope.execT = time.Since(starTime)
ds.debug()
}
if ds.err != nil {
return ds.err
}
return nil
}