diamond-orm/idcounter.go

75 lines
1.5 KiB
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.FindOneOptions = 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("unsupported id type provided")
}
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
switch nini := cnt.Current.(type) {
case int:
if nini == 0 {
cnt.Current = nini + 1
}
case int32:
if nini == int32(0) {
cnt.Current = nini + 1
}
case int64:
if nini == int64(0) {
cnt.Current = nini + 1
}
case uint:
if nini == uint(0) {
cnt.Current = nini + 1
}
case uint32:
if nini == uint32(0) {
cnt.Current = nini + 1
}
case uint64:
if nini == uint64(0) {
cnt.Current = nini + 1
}
case string:
cnt.Current = NextStringID()
case primitive.ObjectID:
cnt.Current = primitive.NewObjectID()
}
}
return cnt.Current
}