diamond-orm/idcounter.go

45 lines
902 B
Go

package orm
import (
"context"
"reflect"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
const COUNTER_COL = "@counters"
type Counter struct {
Current any `bson:"current"`
Collection string `bson:"collection"`
}
func getLastInColl(cname string, id interface{}) interface{} {
var opts = options.FindOne()
switch id.(type) {
case int, int64, int32, uint, uint32, uint64, primitive.ObjectID:
opts.SetSort(bson.M{"_id": -1})
case string:
opts.SetSort(bson.M{"createdAt": -1})
default:
panic(ErrUnsupportedID)
}
var cnt Counter
if !reflect.ValueOf(id).IsZero() {
return id
}
if err := DB.Collection(COUNTER_COL).FindOne(context.TODO(), bson.M{
"collection": cname,
}, opts).Decode(&cnt); err != nil {
cnt = Counter{
Current: id,
}
cnt.Collection = cname
}
return cnt.Current
}