updated mongo driver dependencies to v2

# Conflicts:
#	exerr/constructor.go
#	exerr/dataCategory.go
#	exerr/dataSeverity.go
#	exerr/dataType.go
#	exerr/exerr.go
#	go.mod
#	mongoext/registry.go
#	reflectext/primStrSer.go
#	rfctime/date.go
#	rfctime/rfc3339.go
#	rfctime/rfc3339Nano.go
#	rfctime/seconds.go
#	rfctime/unix.go
#	rfctime/unixMilli.go
#	rfctime/unixNano.go
#	wmo/collection.go
#	wmo/queryInsert.go
This commit is contained in:
2026-04-21 12:11:38 +02:00
parent f62e7499ec
commit 852468f976
36 changed files with 278 additions and 679 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ package cursortoken
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/v2/mongo"
) )
type RawFilter interface { type RawFilter interface {
+7 -7
View File
@@ -3,7 +3,7 @@ package cursortoken
import ( import (
"encoding/base32" "encoding/base32"
"encoding/json" "encoding/json"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/v2/bson"
"time" "time"
) )
@@ -119,18 +119,18 @@ func (c CTKeySort) IsStart() bool {
return c.Mode == CTMStart return c.Mode == CTMStart
} }
func (c CTKeySort) valuePrimaryObjectId() (primitive.ObjectID, bool) { func (c CTKeySort) valuePrimaryObjectId() (bson.ObjectID, bool) {
if oid, err := primitive.ObjectIDFromHex(c.ValuePrimary); err == nil { if oid, err := bson.ObjectIDFromHex(c.ValuePrimary); err == nil {
return oid, true return oid, true
} else { } else {
return primitive.ObjectID{}, false return bson.ObjectID{}, false
} }
} }
func (c CTKeySort) valueSecondaryObjectId() (primitive.ObjectID, bool) { func (c CTKeySort) valueSecondaryObjectId() (bson.ObjectID, bool) {
if oid, err := primitive.ObjectIDFromHex(c.ValueSecondary); err == nil { if oid, err := bson.ObjectIDFromHex(c.ValueSecondary); err == nil {
return oid, true return oid, true
} else { } else {
return primitive.ObjectID{}, false return bson.ObjectID{}, false
} }
} }
+2 -2
View File
@@ -16,7 +16,7 @@ import (
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/v2/bson"
) )
// //
@@ -253,7 +253,7 @@ func (b *Builder) Bytes(key string, val []byte) *Builder {
return b.addMeta(key, MDTBytes, val) return b.addMeta(key, MDTBytes, val)
} }
func (b *Builder) ObjectID(key string, val primitive.ObjectID) *Builder { func (b *Builder) ObjectID(key string, val bson.ObjectID) *Builder {
return b.addMeta(key, MDTObjectID, val) return b.addMeta(key, MDTObjectID, val)
} }
+9 -12
View File
@@ -3,13 +3,14 @@ package exerr
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"maps"
"reflect" "reflect"
"time" "time"
) )
var reflectTypeStr = reflect.TypeOf("") var reflectTypeStr = reflect.TypeFor[string]()
func FromError(err error) *ExErr { func FromError(err error) *ExErr {
@@ -152,20 +153,18 @@ func getForeignMeta(err error) (mm MetaMap) {
}() }()
rval := reflect.ValueOf(err) rval := reflect.ValueOf(err)
if rval.Kind() == reflect.Interface || rval.Kind() == reflect.Ptr { if rval.Kind() == reflect.Interface || rval.Kind() == reflect.Pointer {
rval = reflect.ValueOf(err).Elem() rval = reflect.ValueOf(err).Elem()
} }
mm.add("foreign.errortype", MDTString, rval.Type().String()) mm.add("foreign.errortype", MDTString, rval.Type().String())
for k, v := range addMetaPrefix("foreign", getReflectedMetaValues(err, 8)) { maps.Copy(mm, addMetaPrefix("foreign", getReflectedMetaValues(err, 8)))
mm[k] = v
}
return mm return mm
} }
func getReflectedMetaValues(value interface{}, remainingDepth int) map[string]MetaValue { func getReflectedMetaValues(value any, remainingDepth int) map[string]MetaValue {
if remainingDepth <= 0 { if remainingDepth <= 0 {
return map[string]MetaValue{} return map[string]MetaValue{}
@@ -177,7 +176,7 @@ func getReflectedMetaValues(value interface{}, remainingDepth int) map[string]Me
rval := reflect.ValueOf(value) rval := reflect.ValueOf(value)
if rval.Type().Kind() == reflect.Ptr { if rval.Type().Kind() == reflect.Pointer {
if rval.IsNil() { if rval.IsNil() {
return map[string]MetaValue{"*": {DataType: MDTNil, Value: nil}} return map[string]MetaValue{"*": {DataType: MDTNil, Value: nil}}
@@ -223,7 +222,7 @@ func getReflectedMetaValues(value interface{}, remainingDepth int) map[string]Me
return map[string]MetaValue{"": {DataType: MDTIntArray, Value: ifraw}} return map[string]MetaValue{"": {DataType: MDTIntArray, Value: ifraw}}
case []int32: case []int32:
return map[string]MetaValue{"": {DataType: MDTInt32Array, Value: ifraw}} return map[string]MetaValue{"": {DataType: MDTInt32Array, Value: ifraw}}
case primitive.ObjectID: case bson.ObjectID:
return map[string]MetaValue{"": {DataType: MDTObjectID, Value: ifraw}} return map[string]MetaValue{"": {DataType: MDTObjectID, Value: ifraw}}
case []string: case []string:
return map[string]MetaValue{"": {DataType: MDTStringArray, Value: ifraw}} return map[string]MetaValue{"": {DataType: MDTStringArray, Value: ifraw}}
@@ -237,9 +236,7 @@ func getReflectedMetaValues(value interface{}, remainingDepth int) map[string]Me
fieldname := fieldtype.Name fieldname := fieldtype.Name
if fieldtype.IsExported() { if fieldtype.IsExported() {
for k, v := range addMetaPrefix(fieldname, getReflectedMetaValues(rval.Field(i).Interface(), remainingDepth-1)) { maps.Copy(m, addMetaPrefix(fieldname, getReflectedMetaValues(rval.Field(i).Interface(), remainingDepth-1)))
m[k] = v
}
} }
} }
return m return m
+9 -44
View File
@@ -4,11 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
) )
type ErrorCategory struct{ Category string } type ErrorCategory struct{ Category string }
@@ -28,8 +24,8 @@ func (e ErrorCategory) MarshalJSON() ([]byte, error) {
return json.Marshal(e.Category) return json.Marshal(e.Category)
} }
func (e *ErrorCategory) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (e *ErrorCategory) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -37,11 +33,11 @@ func (e *ErrorCategory) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
*e = ErrorCategory{} *e = ErrorCategory{}
return nil return nil
} }
if bt != bson.TypeString { if bson.Type(bt) != bson.TypeString {
return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bson.Type(bt)))
} }
var tt string var tt string
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -49,40 +45,9 @@ func (e *ErrorCategory) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
return nil return nil
} }
func (e ErrorCategory) MarshalBSONValue() (bsontype.Type, []byte, error) { func (e ErrorCategory) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(e.Category) tp, data, err := bson.MarshalValue(e.Category)
} return byte(tp), data, err
func (e ErrorCategory) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = e.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&e))
} else {
val.Set(reflect.ValueOf(e))
}
return nil
} }
//goland:noinspection GoUnusedGlobalVariable //goland:noinspection GoUnusedGlobalVariable
+9 -44
View File
@@ -4,11 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
) )
type ErrorSeverity struct{ Severity string } type ErrorSeverity struct{ Severity string }
@@ -30,8 +26,8 @@ func (e ErrorSeverity) MarshalJSON() ([]byte, error) {
return json.Marshal(e.Severity) return json.Marshal(e.Severity)
} }
func (e *ErrorSeverity) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (e *ErrorSeverity) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -39,11 +35,11 @@ func (e *ErrorSeverity) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
*e = ErrorSeverity{} *e = ErrorSeverity{}
return nil return nil
} }
if bt != bson.TypeString { if bson.Type(bt) != bson.TypeString {
return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bson.Type(bt)))
} }
var tt string var tt string
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -51,40 +47,9 @@ func (e *ErrorSeverity) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
return nil return nil
} }
func (e ErrorSeverity) MarshalBSONValue() (bsontype.Type, []byte, error) { func (e ErrorSeverity) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(e.Severity) tp, data, err := bson.MarshalValue(e.Severity)
} return byte(tp), data, err
func (e ErrorSeverity) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = e.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&e))
} else {
val.Set(reflect.ValueOf(e))
}
return nil
} }
//goland:noinspection GoUnusedGlobalVariable //goland:noinspection GoUnusedGlobalVariable
+35 -71
View File
@@ -4,14 +4,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"reflect"
"git.blackforestbytes.com/BlackForestBytes/goext/dataext" "git.blackforestbytes.com/BlackForestBytes/goext/dataext"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
) )
type ErrorType struct { type ErrorType struct {
@@ -21,42 +16,42 @@ type ErrorType struct {
//goland:noinspection GoUnusedGlobalVariable //goland:noinspection GoUnusedGlobalVariable
var ( var (
TypeInternal = NewType("INTERNAL_ERROR", langext.Ptr(500)) TypeInternal = NewType("INTERNAL_ERROR", new(500))
TypePanic = NewType("PANIC", langext.Ptr(500)) TypePanic = NewType("PANIC", new(500))
TypeNotImplemented = NewType("NOT_IMPLEMENTED", langext.Ptr(500)) TypeNotImplemented = NewType("NOT_IMPLEMENTED", new(500))
TypeAssert = NewType("ASSERT", langext.Ptr(500)) TypeAssert = NewType("ASSERT", new(500))
TypeMongoQuery = NewType("MONGO_QUERY", langext.Ptr(500)) TypeMongoQuery = NewType("MONGO_QUERY", new(500))
TypeCursorTokenDecode = NewType("CURSOR_TOKEN_DECODE", langext.Ptr(500)) TypeCursorTokenDecode = NewType("CURSOR_TOKEN_DECODE", new(500))
TypeMongoFilter = NewType("MONGO_FILTER", langext.Ptr(500)) TypeMongoFilter = NewType("MONGO_FILTER", new(500))
TypeMongoReflection = NewType("MONGO_REFLECTION", langext.Ptr(500)) TypeMongoReflection = NewType("MONGO_REFLECTION", new(500))
TypeMongoInvalidOpt = NewType("MONGO_INVALIDOPT", langext.Ptr(500)) TypeMongoInvalidOpt = NewType("MONGO_INVALIDOPT", new(500))
TypeSQLQuery = NewType("SQL_QUERY", langext.Ptr(500)) TypeSQLQuery = NewType("SQL_QUERY", new(500))
TypeSQLBuild = NewType("SQL_BUILD", langext.Ptr(500)) TypeSQLBuild = NewType("SQL_BUILD", new(500))
TypeSQLDecode = NewType("SQL_DECODE", langext.Ptr(500)) TypeSQLDecode = NewType("SQL_DECODE", new(500))
TypeWrap = NewType("Wrap", nil) TypeWrap = NewType("Wrap", nil)
TypeBindFailURI = NewType("BINDFAIL_URI", langext.Ptr(400)) TypeBindFailURI = NewType("BINDFAIL_URI", new(400))
TypeBindFailQuery = NewType("BINDFAIL_QUERY", langext.Ptr(400)) TypeBindFailQuery = NewType("BINDFAIL_QUERY", new(400))
TypeBindFailJSON = NewType("BINDFAIL_JSON", langext.Ptr(400)) TypeBindFailJSON = NewType("BINDFAIL_JSON", new(400))
TypeBindFailFormData = NewType("BINDFAIL_FORMDATA", langext.Ptr(400)) TypeBindFailFormData = NewType("BINDFAIL_FORMDATA", new(400))
TypeBindFailHeader = NewType("BINDFAIL_HEADER", langext.Ptr(400)) TypeBindFailHeader = NewType("BINDFAIL_HEADER", new(400))
TypeMarshalEntityID = NewType("MARSHAL_ENTITY_ID", langext.Ptr(400)) TypeMarshalEntityID = NewType("MARSHAL_ENTITY_ID", new(400))
TypeInvalidCSID = NewType("INVALID_CSID", langext.Ptr(400)) TypeInvalidCSID = NewType("INVALID_CSID", new(400))
TypeGoogleStatuscode = NewType("GOOGLE_STATUSCODE", langext.Ptr(400)) TypeGoogleStatuscode = NewType("GOOGLE_STATUSCODE", new(400))
TypeGoogleResponse = NewType("GOOGLE_RESPONSE", langext.Ptr(400)) TypeGoogleResponse = NewType("GOOGLE_RESPONSE", new(400))
TypeUnauthorized = NewType("UNAUTHORIZED", langext.Ptr(401)) TypeUnauthorized = NewType("UNAUTHORIZED", new(401))
TypeAuthFailed = NewType("AUTH_FAILED", langext.Ptr(401)) TypeAuthFailed = NewType("AUTH_FAILED", new(401))
TypeInvalidImage = NewType("IMAGEEXT_INVALID_IMAGE", langext.Ptr(400)) TypeInvalidImage = NewType("IMAGEEXT_INVALID_IMAGE", new(400))
TypeInvalidMimeType = NewType("IMAGEEXT_INVALID_MIMETYPE", langext.Ptr(400)) TypeInvalidMimeType = NewType("IMAGEEXT_INVALID_MIMETYPE", new(400))
TypeWebsocket = NewType("WEBSOCKET", langext.Ptr(500)) TypeWebsocket = NewType("WEBSOCKET", new(500))
// other values come from the downstream application that uses goext // other values come from the downstream application that uses goext
) )
@@ -81,8 +76,8 @@ func (e ErrorType) MarshalJSON() ([]byte, error) {
return json.Marshal(e.Key) return json.Marshal(e.Key)
} }
func (e *ErrorType) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (e *ErrorType) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -90,11 +85,11 @@ func (e *ErrorType) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*e = ErrorType{} *e = ErrorType{}
return nil return nil
} }
if bt != bson.TypeString { if bson.Type(bt) != bson.TypeString {
return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into String", bson.Type(bt)))
} }
var tt string var tt string
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -108,40 +103,9 @@ func (e *ErrorType) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
} }
} }
func (e ErrorType) MarshalBSONValue() (bsontype.Type, []byte, error) { func (e ErrorType) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(e.Key) tp, data, err := bson.MarshalValue(e.Key)
} return byte(tp), data, err
func (e ErrorType) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = e.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&e))
} else {
val.Set(reflect.ValueOf(e))
}
return nil
} }
var registeredTypes = dataext.SyncMap[string, ErrorType]{} var registeredTypes = dataext.SyncMap[string, ErrorType]{}
+14 -15
View File
@@ -3,10 +3,9 @@ package exerr
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"git.blackforestbytes.com/BlackForestBytes/goext/tst" "git.blackforestbytes.com/BlackForestBytes/goext/tst"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"testing" "testing"
"time" "time"
) )
@@ -57,7 +56,7 @@ func TestBSONMarshalErrorCategory(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
defer cancel() defer cancel()
client, err := mongo.Connect(ctx) client, err := mongo.Connect()
if err != nil { if err != nil {
t.Skip("Skip test - no local mongo found") t.Skip("Skip test - no local mongo found")
return return
@@ -68,7 +67,7 @@ func TestBSONMarshalErrorCategory(t *testing.T) {
return return
} }
primimd := primitive.NewObjectID() primimd := bson.NewObjectID()
_, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": CatSystem}) _, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": CatSystem})
tst.AssertNoErr(t, err) tst.AssertNoErr(t, err)
@@ -76,8 +75,8 @@ func TestBSONMarshalErrorCategory(t *testing.T) {
cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}}) cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}})
var c1 struct { var c1 struct {
ID primitive.ObjectID `bson:"_id"` ID bson.ObjectID `bson:"_id"`
Val ErrorCategory `bson:"val"` Val ErrorCategory `bson:"val"`
} }
err = cursor.Decode(&c1) err = cursor.Decode(&c1)
@@ -90,7 +89,7 @@ func TestBSONMarshalErrorSeverity(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
defer cancel() defer cancel()
client, err := mongo.Connect(ctx) client, err := mongo.Connect()
if err != nil { if err != nil {
t.Skip("Skip test - no local mongo found") t.Skip("Skip test - no local mongo found")
return return
@@ -101,7 +100,7 @@ func TestBSONMarshalErrorSeverity(t *testing.T) {
return return
} }
primimd := primitive.NewObjectID() primimd := bson.NewObjectID()
_, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": SevErr}) _, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": SevErr})
tst.AssertNoErr(t, err) tst.AssertNoErr(t, err)
@@ -109,8 +108,8 @@ func TestBSONMarshalErrorSeverity(t *testing.T) {
cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}}) cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}})
var c1 struct { var c1 struct {
ID primitive.ObjectID `bson:"_id"` ID bson.ObjectID `bson:"_id"`
Val ErrorSeverity `bson:"val"` Val ErrorSeverity `bson:"val"`
} }
err = cursor.Decode(&c1) err = cursor.Decode(&c1)
@@ -123,7 +122,7 @@ func TestBSONMarshalErrorType(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
defer cancel() defer cancel()
client, err := mongo.Connect(ctx) client, err := mongo.Connect()
if err != nil { if err != nil {
t.Skip("Skip test - no local mongo found") t.Skip("Skip test - no local mongo found")
return return
@@ -134,7 +133,7 @@ func TestBSONMarshalErrorType(t *testing.T) {
return return
} }
primimd := primitive.NewObjectID() primimd := bson.NewObjectID()
_, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": TypeNotImplemented}) _, err = client.Database("_test").Collection("goext-cicd").InsertOne(ctx, bson.M{"_id": primimd, "val": TypeNotImplemented})
tst.AssertNoErr(t, err) tst.AssertNoErr(t, err)
@@ -142,8 +141,8 @@ func TestBSONMarshalErrorType(t *testing.T) {
cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}}) cursor := client.Database("_test").Collection("goext-cicd").FindOne(ctx, bson.M{"_id": primimd, "val": bson.M{"$type": "string"}})
var c1 struct { var c1 struct {
ID primitive.ObjectID `bson:"_id"` ID bson.ObjectID `bson:"_id"`
Val ErrorType `bson:"val"` Val ErrorType `bson:"val"`
} }
err = cursor.Decode(&c1) err = cursor.Decode(&c1)
+32 -30
View File
@@ -2,9 +2,9 @@ package exerr
import ( import (
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/rs/xid" "github.com/rs/xid"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"reflect" "reflect"
"strings" "strings"
"time" "time"
@@ -125,35 +125,37 @@ func (ee *ExErr) FormatLog(lvl LogPrintLevel) string {
} else if lvl == LogPrintOverview { } else if lvl == LogPrintOverview {
str := "[" + ee.RecursiveType().Key + "] <" + ee.UniqueID + "> " + strings.ReplaceAll(ee.RecursiveMessage(), "\n", " ") + "\n" var str strings.Builder
str.WriteString("[" + ee.RecursiveType().Key + "] <" + ee.UniqueID + "> " + strings.ReplaceAll(ee.RecursiveMessage(), "\n", " ") + "\n")
for exk, exv := range ee.Extra { for exk, exv := range ee.Extra {
str += fmt.Sprintf(" # [[[ %s ==> %v ]]]\n", exk, exv) str.WriteString(fmt.Sprintf(" # [[[ %s ==> %v ]]]\n", exk, exv))
} }
indent := "" var indent strings.Builder
for curr := ee; curr != nil; curr = curr.OriginalError { for curr := ee; curr != nil; curr = curr.OriginalError {
indent += " " indent.WriteString(" ")
str += indent str.WriteString(indent.String())
str += "-> " str.WriteString("-> ")
strmsg := strings.Trim(curr.Message, " \r\n\t") strmsg := strings.Trim(curr.Message, " \r\n\t")
if lbidx := strings.Index(curr.Message, "\n"); lbidx >= 0 { if lbidx := strings.Index(curr.Message, "\n"); lbidx >= 0 {
strmsg = strmsg[0:lbidx] strmsg = strmsg[0:lbidx]
} }
strmsg = langext.StrLimit(strmsg, 61, "...") strmsg = langext.StrLimit(strmsg, 61, "...")
str += strmsg str.WriteString(strmsg)
str += "\n" str.WriteString("\n")
} }
return str return str.String()
} else if lvl == LogPrintFull { } else if lvl == LogPrintFull {
str := "[" + ee.RecursiveType().Key + "] <" + ee.UniqueID + "> " + strings.ReplaceAll(ee.RecursiveMessage(), "\n", " ") + "\n" var str strings.Builder
str.WriteString("[" + ee.RecursiveType().Key + "] <" + ee.UniqueID + "> " + strings.ReplaceAll(ee.RecursiveMessage(), "\n", " ") + "\n")
for exk, exv := range ee.Extra { for exk, exv := range ee.Extra {
str += fmt.Sprintf(" # [[[ %s ==> %v ]]]\n", exk, exv) str.WriteString(fmt.Sprintf(" # [[[ %s ==> %v ]]]\n", exk, exv))
} }
indent := "" indent := ""
@@ -165,33 +167,33 @@ func (ee *ExErr) FormatLog(lvl LogPrintLevel) string {
etype = "~" etype = "~"
} }
str += indent str.WriteString(indent)
str += "-> [" str.WriteString("-> [")
str += etype str.WriteString(etype)
if curr.Category == CatForeign { if curr.Category == CatForeign {
str += "|Foreign" str.WriteString("|Foreign")
} }
str += "] " str.WriteString("] ")
str += strings.ReplaceAll(curr.Message, "\n", " ") str.WriteString(strings.ReplaceAll(curr.Message, "\n", " "))
if curr.Caller != "" { if curr.Caller != "" {
str += " (@ " str.WriteString(" (@ ")
str += curr.Caller str.WriteString(curr.Caller)
str += ")" str.WriteString(")")
} }
str += "\n" str.WriteString("\n")
if curr.Meta.Any() { if curr.Meta.Any() {
meta := indent + " {" + curr.Meta.FormatOneLine(240) + "}" meta := indent + " {" + curr.Meta.FormatOneLine(240) + "}"
if len(meta) < 200 { if len(meta) < 200 {
str += meta str.WriteString(meta)
str += "\n" str.WriteString("\n")
} else { } else {
str += curr.Meta.FormatMultiLine(indent+" ", " ", 1024) str.WriteString(curr.Meta.FormatMultiLine(indent+" ", " ", 1024))
str += "\n" str.WriteString("\n")
} }
} }
} }
return str return str.String()
} else { } else {
@@ -201,7 +203,7 @@ func (ee *ExErr) FormatLog(lvl LogPrintLevel) string {
} }
func (ee *ExErr) ShortLog(evt *zerolog.Event) { func (ee *ExErr) ShortLog(evt *zerolog.Event) {
ee.Meta.Apply(evt, langext.Ptr(240)).Msg(ee.FormatLog(LogPrintShort)) ee.Meta.Apply(evt, new(240)).Msg(ee.FormatLog(LogPrintShort))
} }
// RecursiveMessage returns the message to show // RecursiveMessage returns the message to show
@@ -254,7 +256,7 @@ func (ee *ExErr) RecursiveType() ErrorType {
func (ee *ExErr) RecursiveStatuscode() *int { func (ee *ExErr) RecursiveStatuscode() *int {
for curr := ee; curr != nil; curr = curr.OriginalError { for curr := ee; curr != nil; curr = curr.OriginalError {
if curr.StatusCode != nil { if curr.StatusCode != nil {
return langext.Ptr(*curr.StatusCode) return new(*curr.StatusCode)
} }
} }
@@ -279,7 +281,7 @@ func (ee *ExErr) RecursiveCategory() ErrorCategory {
func (ee *ExErr) RecursiveMeta(key string) *MetaValue { func (ee *ExErr) RecursiveMeta(key string) *MetaValue {
for curr := ee; curr != nil; curr = curr.OriginalError { for curr := ee; curr != nil; curr = curr.OriginalError {
if metaval, ok := curr.Meta[key]; ok { if metaval, ok := curr.Meta[key]; ok {
return langext.Ptr(metaval) return new(metaval)
} }
} }
+9 -10
View File
@@ -7,8 +7,7 @@ import (
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"math" "math"
"strconv" "strconv"
"strings" "strings"
@@ -99,7 +98,7 @@ func (v MetaValue) SerializeValue() (string, error) {
case MDTBytes: case MDTBytes:
return hex.EncodeToString(v.Value.([]byte)), nil return hex.EncodeToString(v.Value.([]byte)), nil
case MDTObjectID: case MDTObjectID:
return v.Value.(primitive.ObjectID).Hex(), nil return v.Value.(bson.ObjectID).Hex(), nil
case MDTTime: case MDTTime:
return strconv.FormatInt(v.Value.(time.Time).Unix(), 10) + "|" + strconv.FormatInt(int64(v.Value.(time.Time).Nanosecond()), 10), nil return strconv.FormatInt(v.Value.(time.Time).Unix(), 10) + "|" + strconv.FormatInt(int64(v.Value.(time.Time).Nanosecond()), 10), nil
case MDTDuration: case MDTDuration:
@@ -178,7 +177,7 @@ func (v MetaValue) ShortString(lim int) string {
case MDTBytes: case MDTBytes:
return langext.StrLimit(hex.EncodeToString(v.Value.([]byte)), lim, "...") return langext.StrLimit(hex.EncodeToString(v.Value.([]byte)), lim, "...")
case MDTObjectID: case MDTObjectID:
return v.Value.(primitive.ObjectID).Hex() return v.Value.(bson.ObjectID).Hex()
case MDTTime: case MDTTime:
return v.Value.(time.Time).Format(time.RFC3339) return v.Value.(time.Time).Format(time.RFC3339)
case MDTDuration: case MDTDuration:
@@ -266,7 +265,7 @@ func (v MetaValue) Apply(key string, evt *zerolog.Event, limitLen *int) *zerolog
case MDTBytes: case MDTBytes:
return evt.Bytes(key, v.Value.([]byte)) return evt.Bytes(key, v.Value.([]byte))
case MDTObjectID: case MDTObjectID:
return evt.Str(key, v.Value.(primitive.ObjectID).Hex()) return evt.Str(key, v.Value.(bson.ObjectID).Hex())
case MDTTime: case MDTTime:
return evt.Time(key, v.Value.(time.Time)) return evt.Time(key, v.Value.(time.Time))
case MDTDuration: case MDTDuration:
@@ -460,7 +459,7 @@ func (v *MetaValue) Deserialize(value string, datatype metaDataType) error {
v.DataType = datatype v.DataType = datatype
return nil return nil
case MDTObjectID: case MDTObjectID:
r, err := primitive.ObjectIDFromHex(value) r, err := bson.ObjectIDFromHex(value)
if err != nil { if err != nil {
return err return err
} }
@@ -577,7 +576,7 @@ func (v MetaValue) ValueString() string {
case MDTBytes: case MDTBytes:
return hex.EncodeToString(v.Value.([]byte)) return hex.EncodeToString(v.Value.([]byte))
case MDTObjectID: case MDTObjectID:
return v.Value.(primitive.ObjectID).Hex() return v.Value.(bson.ObjectID).Hex()
case MDTTime: case MDTTime:
return v.Value.(time.Time).Format(time.RFC3339Nano) return v.Value.(time.Time).Format(time.RFC3339Nano)
case MDTDuration: case MDTDuration:
@@ -628,8 +627,8 @@ func (v MetaValue) rawValueForJson() any {
if v.Value.(AnyWrap).IsError { if v.Value.(AnyWrap).IsError {
return bson.M{"@error": true} return bson.M{"@error": true}
} }
jsonobj := primitive.M{} jsonobj := bson.M{}
jsonarr := primitive.A{} jsonarr := bson.A{}
if err := json.Unmarshal([]byte(v.Value.(AnyWrap).Json), &jsonobj); err == nil { if err := json.Unmarshal([]byte(v.Value.(AnyWrap).Json), &jsonobj); err == nil {
return jsonobj return jsonobj
} else if err := json.Unmarshal([]byte(v.Value.(AnyWrap).Json), &jsonarr); err == nil { } else if err := json.Unmarshal([]byte(v.Value.(AnyWrap).Json), &jsonarr); err == nil {
@@ -654,7 +653,7 @@ func (v MetaValue) rawValueForJson() any {
return v.Value.(time.Time).Format(time.RFC3339Nano) return v.Value.(time.Time).Format(time.RFC3339Nano)
} }
if v.DataType == MDTObjectID { if v.DataType == MDTObjectID {
return v.Value.(primitive.ObjectID).Hex() return v.Value.(bson.ObjectID).Hex()
} }
if v.DataType == MDTNil { if v.DataType == MDTNil {
return nil return nil
+11 -10
View File
@@ -1,14 +1,14 @@
module git.blackforestbytes.com/BlackForestBytes/goext module git.blackforestbytes.com/BlackForestBytes/goext
go 1.25.0 go 1.26.0
require ( require (
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/glebarez/go-sqlite v1.22.0 // only needed for tests -.- github.com/glebarez/go-sqlite v1.22.0 // only needed for tests -.-
github.com/jmoiron/sqlx v1.4.0 github.com/jmoiron/sqlx v1.4.0
github.com/rs/xid v1.6.0 github.com/rs/xid v1.6.0
github.com/rs/zerolog v1.35.0 github.com/rs/zerolog v1.35.1
go.mongodb.org/mongo-driver v1.17.9 go.mongodb.org/mongo-driver/v2 v2.5.1
golang.org/x/crypto v0.50.0 golang.org/x/crypto v0.50.0
golang.org/x/sys v0.43.0 golang.org/x/sys v0.43.0
golang.org/x/term v0.42.0 golang.org/x/term v0.42.0
@@ -20,7 +20,7 @@ require (
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/jung-kurt/gofpdf v1.16.2 github.com/jung-kurt/gofpdf v1.16.2
github.com/xuri/excelize/v2 v2.10.1 github.com/xuri/excelize/v2 v2.10.1
golang.org/x/net v0.53.0 go.mongodb.org/mongo-driver v1.17.9
golang.org/x/sync v0.20.0 golang.org/x/sync v0.20.0
) )
@@ -38,7 +38,7 @@ require (
github.com/goccy/go-json v0.10.6 // indirect github.com/goccy/go-json v0.10.6 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/golang/snappy v1.0.0 // indirect github.com/golang/snappy v1.0.0 // indirect
github.com/google/uuid v1.5.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.5 // indirect github.com/klauspost/compress v1.18.5 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
@@ -49,6 +49,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/montanaflynn/stats v0.9.0 // indirect github.com/montanaflynn/stats v0.9.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.3.0 // indirect github.com/pelletier/go-toml/v2 v2.3.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect
@@ -64,13 +65,13 @@ require (
github.com/xuri/efp v0.0.1 // indirect github.com/xuri/efp v0.0.1 // indirect
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.26.0 // indirect golang.org/x/arch v0.26.0 // indirect
golang.org/x/image v0.39.0 // indirect golang.org/x/image v0.39.0 // indirect
golang.org/x/net v0.53.0 // indirect
golang.org/x/text v0.36.0 // indirect golang.org/x/text v0.36.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect google.golang.org/protobuf v1.36.11 // indirect
modernc.org/libc v1.37.6 // indirect modernc.org/libc v1.72.0 // indirect
modernc.org/mathutil v1.6.0 // indirect modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.7.2 // indirect modernc.org/memory v1.11.0 // indirect
modernc.org/sqlite v1.28.0 // indirect modernc.org/sqlite v1.49.1 // indirect
) )
+2 -2
View File
@@ -1,8 +1,8 @@
package mongoext package mongoext
import ( import (
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/v2/mongo"
) )
// FixTextSearchPipeline moves {$match:{$text:{$search}}} entries to the front of the pipeline (otherwise its an mongo error) // FixTextSearchPipeline moves {$match:{$text:{$search}}} entries to the front of the pipeline (otherwise its an mongo error)
+1 -1
View File
@@ -1,7 +1,7 @@
package mongoext package mongoext
import ( import (
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"reflect" "reflect"
"strings" "strings"
) )
+5 -39
View File
@@ -1,51 +1,17 @@
package mongoext package mongoext
import ( import (
"git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/rfctime"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/primitive"
"reflect" "reflect"
"go.mongodb.org/mongo-driver/v2/bson"
) )
func CreateGoExtBsonRegistry() *bsoncodec.Registry { func CreateGoExtBsonRegistry() *bson.Registry {
reg := bson.NewRegistry() reg := bson.NewRegistry()
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.RFC3339Time{}), rfctime.RFC3339Time{}) // otherwise we get []bson.E when unmarshalling into any
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.RFC3339Time{}), rfctime.RFC3339Time{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.RFC3339NanoTime{}), rfctime.RFC3339NanoTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.RFC3339NanoTime{}), rfctime.RFC3339NanoTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.UnixTime{}), rfctime.UnixTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.UnixTime{}), rfctime.UnixTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.UnixMilliTime{}), rfctime.UnixMilliTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.UnixMilliTime{}), rfctime.UnixMilliTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.UnixNanoTime{}), rfctime.UnixNanoTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.UnixNanoTime{}), rfctime.UnixNanoTime{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.Date{}), rfctime.Date{})
reg.RegisterTypeDecoder(reflect.TypeOf(&rfctime.Date{}), rfctime.Date{})
reg.RegisterTypeDecoder(reflect.TypeOf(rfctime.SecondsF64(0)), rfctime.SecondsF64(0))
reg.RegisterTypeDecoder(reflect.TypeOf(langext.Ptr(rfctime.SecondsF64(0))), rfctime.SecondsF64(0))
reg.RegisterTypeDecoder(reflect.TypeOf(exerr.ErrorCategory{}), exerr.ErrorCategory{})
reg.RegisterTypeDecoder(reflect.TypeOf(langext.Ptr(exerr.ErrorCategory{})), exerr.ErrorCategory{})
reg.RegisterTypeDecoder(reflect.TypeOf(exerr.ErrorSeverity{}), exerr.ErrorSeverity{})
reg.RegisterTypeDecoder(reflect.TypeOf(langext.Ptr(exerr.ErrorSeverity{})), exerr.ErrorSeverity{})
reg.RegisterTypeDecoder(reflect.TypeOf(exerr.ErrorType{}), exerr.ErrorType{})
reg.RegisterTypeDecoder(reflect.TypeOf(langext.Ptr(exerr.ErrorType{})), exerr.ErrorType{})
// otherwise we get []primitve.E when unmarshalling into any
// which will result in {'key': .., 'value': ...}[] json when json-marshalling // which will result in {'key': .., 'value': ...}[] json when json-marshalling
reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeOf(primitive.M{})) reg.RegisterTypeMapEntry(bson.TypeEmbeddedDocument, reflect.TypeFor[bson.M]())
return reg return reg
} }
+2 -2
View File
@@ -2,8 +2,8 @@ package pagination
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/v2/mongo"
) )
type MongoFilter interface { type MongoFilter interface {
+17 -17
View File
@@ -3,8 +3,8 @@ package reflectext
import ( import (
"errors" "errors"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
@@ -13,24 +13,24 @@ import (
var primitiveSerializer = map[reflect.Type]genSerializer{ var primitiveSerializer = map[reflect.Type]genSerializer{
reflect.TypeOf(""): newGenSerializer(serStringToString, serStringToString), reflect.TypeFor[string](): newGenSerializer(serStringToString, serStringToString),
reflect.TypeOf(int(0)): newGenSerializer(serIntNumToString[int], serStringToSIntNum[int]), reflect.TypeFor[int](): newGenSerializer(serIntNumToString[int], serStringToSIntNum[int]),
reflect.TypeOf(int32(0)): newGenSerializer(serIntNumToString[int32], serStringToSIntNum[int32]), reflect.TypeFor[int32](): newGenSerializer(serIntNumToString[int32], serStringToSIntNum[int32]),
reflect.TypeOf(int64(0)): newGenSerializer(serIntNumToString[int64], serStringToSIntNum[int64]), reflect.TypeFor[int64](): newGenSerializer(serIntNumToString[int64], serStringToSIntNum[int64]),
reflect.TypeOf(uint(0)): newGenSerializer(serIntNumToString[uint], serStringToUIntNum[uint]), reflect.TypeFor[uint](): newGenSerializer(serIntNumToString[uint], serStringToUIntNum[uint]),
reflect.TypeOf(uint32(0)): newGenSerializer(serIntNumToString[uint32], serStringToUIntNum[uint32]), reflect.TypeFor[uint32](): newGenSerializer(serIntNumToString[uint32], serStringToUIntNum[uint32]),
reflect.TypeOf(uint64(0)): newGenSerializer(serIntNumToString[uint64], serStringToUIntNum[uint64]), reflect.TypeFor[uint64](): newGenSerializer(serIntNumToString[uint64], serStringToUIntNum[uint64]),
reflect.TypeOf(float32(0)): newGenSerializer(serFloatNumToString[float32], serStringToFloatNum[float32]), reflect.TypeFor[float32](): newGenSerializer(serFloatNumToString[float32], serStringToFloatNum[float32]),
reflect.TypeOf(float64(0)): newGenSerializer(serFloatNumToString[float64], serStringToFloatNum[float64]), reflect.TypeFor[float64](): newGenSerializer(serFloatNumToString[float64], serStringToFloatNum[float64]),
reflect.TypeOf(true): newGenSerializer(serBoolToString, serStringToBool), reflect.TypeFor[bool](): newGenSerializer(serBoolToString, serStringToBool),
reflect.TypeOf(primitive.ObjectID{}): newGenSerializer(serObjectIDToString, serStringToObjectID), reflect.TypeFor[bson.ObjectID](): newGenSerializer(serObjectIDToString, serStringToObjectID),
reflect.TypeOf(time.Time{}): newGenSerializer(serTimeToString, serStringToTime), reflect.TypeFor[time.Time](): newGenSerializer(serTimeToString, serStringToTime),
} }
type genSerializer struct { type genSerializer struct {
@@ -111,15 +111,15 @@ func serStringToBool(v string) (bool, error) {
return false, errors.New(fmt.Sprintf("invalid boolean value '%s'", v)) return false, errors.New(fmt.Sprintf("invalid boolean value '%s'", v))
} }
func serObjectIDToString(v primitive.ObjectID) (string, error) { func serObjectIDToString(v bson.ObjectID) (string, error) {
return v.Hex(), nil return v.Hex(), nil
} }
func serStringToObjectID(v string) (primitive.ObjectID, error) { func serStringToObjectID(v string) (bson.ObjectID, error) {
if rv, err := primitive.ObjectIDFromHex(v); err == nil { if rv, err := bson.ObjectIDFromHex(v); err == nil {
return rv, nil return rv, nil
} else { } else {
return primitive.ObjectID{}, err return bson.ObjectID{}, err
} }
} }
+13 -44
View File
@@ -4,11 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -83,8 +79,8 @@ func (t *Date) UnmarshalText(data []byte) error {
return t.ParseString(string(data)) return t.ParseString(string(data))
} }
func (t *Date) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *Date) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bsontype.Null { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -92,12 +88,12 @@ func (t *Date) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*t = Date{} *t = Date{}
return nil return nil
} }
if bt != bsontype.String { if bson.Type(bt) != bson.TypeString {
return errors.New(fmt.Sprintf("cannot unmarshal %v into Date", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into Date", bson.Type(bt)))
} }
var tt string var tt string
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -120,43 +116,16 @@ func (t *Date) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
return nil return nil
} }
func (t Date) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t Date) MarshalBSONValue() (byte, []byte, error) {
var tp bson.Type
var data []byte
var err error
if t.IsZero() { if t.IsZero() {
return bson.MarshalValue("") tp, data, err = bson.MarshalValue("")
}
return bson.MarshalValue(t.String())
}
func (t Date) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else { } else {
val.Set(reflect.ValueOf(t)) tp, data, err = bson.MarshalValue(t.String())
} }
return byte(tp), data, err
return nil
} }
func (t Date) Serialize() string { func (t Date) Serialize() string {
+10 -46
View File
@@ -4,14 +4,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"reflect"
"time" "time"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
) )
type RFC3339Time time.Time type RFC3339Time time.Time
@@ -70,8 +65,8 @@ func (t *RFC3339Time) UnmarshalText(data []byte) error {
return nil return nil
} }
func (t *RFC3339Time) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *RFC3339Time) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -79,11 +74,11 @@ func (t *RFC3339Time) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*t = RFC3339Time{} *t = RFC3339Time{}
return nil return nil
} }
if bt != bson.TypeDateTime { if bson.Type(bt) != bson.TypeDateTime {
return errors.New(fmt.Sprintf("cannot unmarshal %v into RFC3339Time", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into RFC3339Time", bson.Type(bt)))
} }
var tt time.Time var tt time.Time
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -91,40 +86,9 @@ func (t *RFC3339Time) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
return nil return nil
} }
func (t RFC3339Time) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t RFC3339Time) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(time.Time(t)) tp, data, err := bson.MarshalValue(time.Time(t))
} return byte(tp), data, err
func (t RFC3339Time) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else {
val.Set(reflect.ValueOf(t))
}
return nil
} }
func (t RFC3339Time) Serialize() string { func (t RFC3339Time) Serialize() string {
@@ -258,7 +222,7 @@ func NewRFC3339Ptr(t *time.Time) *RFC3339Time {
if t == nil { if t == nil {
return nil return nil
} }
return langext.Ptr(RFC3339Time(*t)) return new(RFC3339Time(*t))
} }
func NowRFC3339() RFC3339Time { func NowRFC3339() RFC3339Time {
+10 -46
View File
@@ -4,12 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"time" "time"
) )
@@ -69,8 +64,8 @@ func (t *RFC3339NanoTime) UnmarshalText(data []byte) error {
return nil return nil
} }
func (t *RFC3339NanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *RFC3339NanoTime) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -78,11 +73,11 @@ func (t *RFC3339NanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) erro
*t = RFC3339NanoTime{} *t = RFC3339NanoTime{}
return nil return nil
} }
if bt != bson.TypeDateTime { if bson.Type(bt) != bson.TypeDateTime {
return errors.New(fmt.Sprintf("cannot unmarshal %v into RFC3339NanoTime", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into RFC3339NanoTime", bson.Type(bt)))
} }
var tt time.Time var tt time.Time
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -90,40 +85,9 @@ func (t *RFC3339NanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) erro
return nil return nil
} }
func (t RFC3339NanoTime) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t RFC3339NanoTime) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(time.Time(t)) tp, data, err := bson.MarshalValue(time.Time(t))
} return byte(tp), data, err
func (t RFC3339NanoTime) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else {
val.Set(reflect.ValueOf(t))
}
return nil
} }
func (t RFC3339NanoTime) Serialize() string { func (t RFC3339NanoTime) Serialize() string {
@@ -257,7 +221,7 @@ func NewRFC3339NanoPtr(t *time.Time) *RFC3339NanoTime {
if t == nil { if t == nil {
return nil return nil
} }
return langext.Ptr(RFC3339NanoTime(*t)) return new(RFC3339NanoTime(*t))
} }
func NowRFC3339Nano() RFC3339NanoTime { func NowRFC3339Nano() RFC3339NanoTime {
+9 -44
View File
@@ -5,11 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/timeext" "git.blackforestbytes.com/BlackForestBytes/goext/timeext"
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"time" "time"
) )
@@ -61,8 +57,8 @@ func (d SecondsF64) MarshalJSON() ([]byte, error) {
return json.Marshal(secs) return json.Marshal(secs)
} }
func (d *SecondsF64) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (d *SecondsF64) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -70,11 +66,11 @@ func (d *SecondsF64) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*d = SecondsF64(0) *d = SecondsF64(0)
return nil return nil
} }
if bt != bson.TypeDouble { if bson.Type(bt) != bson.TypeDouble {
return errors.New(fmt.Sprintf("cannot unmarshal %v into SecondsF64", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into SecondsF64", bson.Type(bt)))
} }
var secValue float64 var secValue float64
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&secValue) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&secValue)
if err != nil { if err != nil {
return err return err
} }
@@ -82,40 +78,9 @@ func (d *SecondsF64) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
return nil return nil
} }
func (d SecondsF64) MarshalBSONValue() (bsontype.Type, []byte, error) { func (d SecondsF64) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(d.Seconds()) tp, data, err := bson.MarshalValue(d.Seconds())
} return byte(tp), data, err
func (d SecondsF64) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = d.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&d))
} else {
val.Set(reflect.ValueOf(d))
}
return nil
} }
func NewSecondsF64(t time.Duration) SecondsF64 { func NewSecondsF64(t time.Duration) SecondsF64 {
+10 -46
View File
@@ -4,12 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"strconv" "strconv"
"time" "time"
) )
@@ -67,8 +62,8 @@ func (t *UnixTime) UnmarshalText(data []byte) error {
return nil return nil
} }
func (t *UnixTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *UnixTime) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -76,11 +71,11 @@ func (t *UnixTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*t = UnixTime{} *t = UnixTime{}
return nil return nil
} }
if bt != bson.TypeDateTime { if bson.Type(bt) != bson.TypeDateTime {
return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixTime", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixTime", bson.Type(bt)))
} }
var tt time.Time var tt time.Time
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -88,40 +83,9 @@ func (t *UnixTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
return nil return nil
} }
func (t UnixTime) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t UnixTime) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(time.Time(t)) tp, data, err := bson.MarshalValue(time.Time(t))
} return byte(tp), data, err
func (t UnixTime) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else {
val.Set(reflect.ValueOf(t))
}
return nil
} }
func (t UnixTime) Serialize() string { func (t UnixTime) Serialize() string {
@@ -251,7 +215,7 @@ func NewUnixPtr(t *time.Time) *UnixTime {
if t == nil { if t == nil {
return nil return nil
} }
return langext.Ptr(UnixTime(*t)) return new(UnixTime(*t))
} }
func NowUnix() UnixTime { func NowUnix() UnixTime {
+10 -46
View File
@@ -4,12 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"strconv" "strconv"
"time" "time"
) )
@@ -67,8 +62,8 @@ func (t *UnixMilliTime) UnmarshalText(data []byte) error {
return nil return nil
} }
func (t *UnixMilliTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *UnixMilliTime) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -76,11 +71,11 @@ func (t *UnixMilliTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
*t = UnixMilliTime{} *t = UnixMilliTime{}
return nil return nil
} }
if bt != bson.TypeDateTime { if bson.Type(bt) != bson.TypeDateTime {
return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixMilliTime", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixMilliTime", bson.Type(bt)))
} }
var tt time.Time var tt time.Time
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -88,40 +83,9 @@ func (t *UnixMilliTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error
return nil return nil
} }
func (t UnixMilliTime) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t UnixMilliTime) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(time.Time(t)) tp, data, err := bson.MarshalValue(time.Time(t))
} return byte(tp), data, err
func (t UnixMilliTime) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else {
val.Set(reflect.ValueOf(t))
}
return nil
} }
func (t UnixMilliTime) Serialize() string { func (t UnixMilliTime) Serialize() string {
@@ -251,7 +215,7 @@ func NewUnixMilliPtr(t *time.Time) *UnixMilliTime {
if t == nil { if t == nil {
return nil return nil
} }
return langext.Ptr(UnixMilliTime(*t)) return new(UnixMilliTime(*t))
} }
func NowUnixMilli() UnixMilliTime { func NowUnixMilli() UnixMilliTime {
+10 -46
View File
@@ -4,12 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"reflect"
"strconv" "strconv"
"time" "time"
) )
@@ -67,8 +62,8 @@ func (t *UnixNanoTime) UnmarshalText(data []byte) error {
return nil return nil
} }
func (t *UnixNanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error { func (t *UnixNanoTime) UnmarshalBSONValue(bt byte, data []byte) error {
if bt == bson.TypeNull { if bson.Type(bt) == bson.TypeNull {
// we can't set nil in UnmarshalBSONValue (so we use default(struct)) // we can't set nil in UnmarshalBSONValue (so we use default(struct))
// Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values // Use mongoext.CreateGoExtBsonRegistry if you need to unmarsh pointer values
// https://stackoverflow.com/questions/75167597 // https://stackoverflow.com/questions/75167597
@@ -76,11 +71,11 @@ func (t *UnixNanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
*t = UnixNanoTime{} *t = UnixNanoTime{}
return nil return nil
} }
if bt != bson.TypeDateTime { if bson.Type(bt) != bson.TypeDateTime {
return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixNanoTime", bt)) return errors.New(fmt.Sprintf("cannot unmarshal %v into UnixNanoTime", bson.Type(bt)))
} }
var tt time.Time var tt time.Time
err := bson.RawValue{Type: bt, Value: data}.Unmarshal(&tt) err := bson.RawValue{Type: bson.Type(bt), Value: data}.Unmarshal(&tt)
if err != nil { if err != nil {
return err return err
} }
@@ -88,40 +83,9 @@ func (t *UnixNanoTime) UnmarshalBSONValue(bt bsontype.Type, data []byte) error {
return nil return nil
} }
func (t UnixNanoTime) MarshalBSONValue() (bsontype.Type, []byte, error) { func (t UnixNanoTime) MarshalBSONValue() (byte, []byte, error) {
return bson.MarshalValue(time.Time(t)) tp, data, err := bson.MarshalValue(time.Time(t))
} return byte(tp), data, err
func (t UnixNanoTime) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
if val.Kind() == reflect.Ptr && val.IsNil() {
if !val.CanSet() {
return errors.New("ValueUnmarshalerDecodeValue")
}
val.Set(reflect.New(val.Type().Elem()))
}
tp, src, err := bsonrw.Copier{}.CopyValueToBytes(vr)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr && len(src) == 0 {
val.Set(reflect.Zero(val.Type()))
return nil
}
err = t.UnmarshalBSONValue(tp, src)
if err != nil {
return err
}
if val.Kind() == reflect.Ptr {
val.Set(reflect.ValueOf(&t))
} else {
val.Set(reflect.ValueOf(t))
}
return nil
} }
func (t UnixNanoTime) Serialize() string { func (t UnixNanoTime) Serialize() string {
@@ -251,7 +215,7 @@ func NewUnixNanoPtr(t *time.Time) *UnixNanoTime {
if t == nil { if t == nil {
return nil return nil
} }
return langext.Ptr(UnixNanoTime(*t)) return new(UnixNanoTime(*t))
} }
func NowUnixNano() UnixNanoTime { func NowUnixNano() UnixNanoTime {
+3 -4
View File
@@ -2,16 +2,15 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/mongo"
ct "git.blackforestbytes.com/BlackForestBytes/goext/cursortoken" ct "git.blackforestbytes.com/BlackForestBytes/goext/cursortoken"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/mongo"
"reflect" "reflect"
) )
type EntityID interface { type EntityID interface {
MarshalBSONValue() (bsontype.Type, []byte, error) MarshalBSONValue() (byte, []byte, error)
String() string String() string
} }
@@ -80,7 +79,7 @@ func (c *Coll[TData]) WithDecodeFunc(cdf func(ctx context.Context, dec Decodable
c.EnsureInitializedReflection(example) c.EnsureInitializedReflection(example)
c.customDecoder = langext.Ptr(cdf) c.customDecoder = new(cdf)
return c return c
} }
+1 -1
View File
@@ -2,8 +2,8 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"go.mongodb.org/mongo-driver/v2/bson"
) )
func (c *Coll[TData]) decodeSingle(ctx context.Context, dec Decodable) (TData, error) { func (c *Coll[TData]) decodeSingle(ctx context.Context, dec Decodable) (TData, error) {
+1 -1
View File
@@ -1,6 +1,6 @@
package wmo package wmo
import "go.mongodb.org/mongo-driver/mongo" import "go.mongodb.org/mongo-driver/v2/mongo"
func W[TData any](collection *mongo.Collection) *Coll[TData] { func W[TData any](collection *mongo.Collection) *Coll[TData] {
c := Coll[TData]{coll: collection} c := Coll[TData]{coll: collection}
+5 -5
View File
@@ -2,13 +2,13 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
) )
func (c *Coll[TData]) Aggregate(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) ([]TData, error) { func (c *Coll[TData]) Aggregate(ctx context.Context, pipeline mongo.Pipeline, opts ...options.Lister[options.AggregateOptions]) ([]TData, error) {
for _, ppl := range c.extraModPipeline { for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx)) pipeline = langext.ArrConcat(pipeline, ppl(ctx))
@@ -29,7 +29,7 @@ func (c *Coll[TData]) Aggregate(ctx context.Context, pipeline mongo.Pipeline, op
return res, nil return res, nil
} }
func (c *Coll[TData]) AggregateOneOpt(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) (*TData, error) { func (c *Coll[TData]) AggregateOneOpt(ctx context.Context, pipeline mongo.Pipeline, opts ...options.Lister[options.AggregateOptions]) (*TData, error) {
for _, ppl := range c.extraModPipeline { for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx)) pipeline = langext.ArrConcat(pipeline, ppl(ctx))
@@ -53,7 +53,7 @@ func (c *Coll[TData]) AggregateOneOpt(ctx context.Context, pipeline mongo.Pipeli
return nil, nil return nil, nil
} }
func (c *Coll[TData]) AggregateOne(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) (TData, error) { func (c *Coll[TData]) AggregateOne(ctx context.Context, pipeline mongo.Pipeline, opts ...options.Lister[options.AggregateOptions]) (TData, error) {
for _, ppl := range c.extraModPipeline { for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx)) pipeline = langext.ArrConcat(pipeline, ppl(ctx))
+2 -2
View File
@@ -2,9 +2,9 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
) )
func (c *Coll[TData]) DeleteOneByID(ctx context.Context, id EntityID) error { func (c *Coll[TData]) DeleteOneByID(ctx context.Context, id EntityID) error {
+9 -22
View File
@@ -2,11 +2,11 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"iter" "iter"
) )
@@ -51,13 +51,15 @@ func (c *Coll[TData]) createFindQuery(ctx context.Context, filter bson.M, opts .
} }
} }
convOpts := make([]*options.AggregateOptions, 0, len(opts)) convOpts := make([]options.Lister[options.AggregateOptions], 0, len(opts))
for _, v := range opts { for _, v := range opts {
vConv, err := convertFindOpt(v) vConv, err := convertFindOpt(v)
if err != nil { if err != nil {
return nil, exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Str("collection", c.Name()).Build() return nil, exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Str("collection", c.Name()).Build()
} }
convOpts = append(convOpts, vConv) if vConv != nil {
convOpts = append(convOpts, vConv)
}
} }
cursor, err := c.coll.Aggregate(ctx, pipeline, convOpts...) cursor, err := c.coll.Aggregate(ctx, pipeline, convOpts...)
@@ -137,7 +139,7 @@ func (c *Coll[TData]) FindIterate(ctx context.Context, filter bson.M, opts ...*o
} }
// converts FindOptions to AggregateOptions // converts FindOptions to AggregateOptions
func convertFindOpt(v *options.FindOptions) (*options.AggregateOptions, error) { func convertFindOpt(v *options.FindOptions) (*options.AggregateOptionsBuilder, error) {
if v == nil { if v == nil {
return nil, nil return nil, nil
} }
@@ -157,7 +159,7 @@ func convertFindOpt(v *options.FindOptions) (*options.AggregateOptions, error) {
r.SetCollation(v.Collation) r.SetCollation(v.Collation)
} }
if v.Comment != nil { if v.Comment != nil {
r.SetComment(*v.Comment) r.SetComment(v.Comment)
} }
if v.CursorType != nil { if v.CursorType != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'CursorType' (cannot convert to AggregateOptions)").Build() return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'CursorType' (cannot convert to AggregateOptions)").Build()
@@ -165,33 +167,18 @@ func convertFindOpt(v *options.FindOptions) (*options.AggregateOptions, error) {
if v.Hint != nil { if v.Hint != nil {
r.SetHint(v.Hint) r.SetHint(v.Hint)
} }
if v.Max != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'Max' (cannot convert to AggregateOptions)").Build()
}
if v.MaxAwaitTime != nil { if v.MaxAwaitTime != nil {
r.SetMaxAwaitTime(*v.MaxAwaitTime) r.SetMaxAwaitTime(*v.MaxAwaitTime)
} }
if v.MaxTime != nil {
r.SetMaxTime(*v.MaxTime)
}
if v.Min != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'Min' (cannot convert to AggregateOptions)").Build()
}
if v.NoCursorTimeout != nil { if v.NoCursorTimeout != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'NoCursorTimeout' (cannot convert to AggregateOptions)").Build() return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'NoCursorTimeout' (cannot convert to AggregateOptions)").Build()
} }
if v.OplogReplay != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'OplogReplay' (cannot convert to AggregateOptions)").Build()
}
if v.ReturnKey != nil { if v.ReturnKey != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'ReturnKey' (cannot convert to AggregateOptions)").Build() return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'ReturnKey' (cannot convert to AggregateOptions)").Build()
} }
if v.ShowRecordID != nil { if v.ShowRecordID != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'ShowRecordID' (cannot convert to AggregateOptions)").Build() return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'ShowRecordID' (cannot convert to AggregateOptions)").Build()
} }
if v.Snapshot != nil {
return nil, exerr.New(exerr.TypeMongoInvalidOpt, "Invalid option 'Snapshot' (cannot convert to AggregateOptions)").Build()
}
if v.Let != nil { if v.Let != nil {
r.SetLet(v.Let) r.SetLet(v.Let)
} }
+2 -2
View File
@@ -3,10 +3,10 @@ package wmo
import ( import (
"context" "context"
"errors" "errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
) )
func (c *Coll[TData]) FindOne(ctx context.Context, filter bson.M) (TData, error) { func (c *Coll[TData]) FindOne(ctx context.Context, filter bson.M) (TData, error) {
+3 -3
View File
@@ -2,10 +2,10 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
) )
func (c *Coll[TData]) InsertOne(ctx context.Context, valueIn TData) (TData, error) { func (c *Coll[TData]) InsertOne(ctx context.Context, valueIn TData) (TData, error) {
@@ -41,7 +41,7 @@ func (c *Coll[TData]) InsertOneUnchecked(ctx context.Context, valueIn any) (TDat
func (c *Coll[TData]) InsertMany(ctx context.Context, valueIn []TData) (*mongo.InsertManyResult, error) { func (c *Coll[TData]) InsertMany(ctx context.Context, valueIn []TData) (*mongo.InsertManyResult, error) {
for _, hook := range c.marshalHooks { for _, hook := range c.marshalHooks {
for i := 0; i < len(valueIn); i++ { for i := range valueIn {
valueIn[i] = hook(valueIn[i]) valueIn[i] = hook(valueIn[i])
} }
} }
+2 -2
View File
@@ -2,11 +2,11 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
ct "git.blackforestbytes.com/BlackForestBytes/goext/cursortoken" ct "git.blackforestbytes.com/BlackForestBytes/goext/cursortoken"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"iter" "iter"
) )
+2 -2
View File
@@ -2,11 +2,11 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
pag "git.blackforestbytes.com/BlackForestBytes/goext/pagination" pag "git.blackforestbytes.com/BlackForestBytes/goext/pagination"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"iter" "iter"
) )
+3 -3
View File
@@ -2,10 +2,10 @@ package wmo
import ( import (
"context" "context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
) )
func (c *Coll[TData]) FindOneAndUpdate(ctx context.Context, filterQuery bson.M, updateQuery bson.M) (TData, error) { func (c *Coll[TData]) FindOneAndUpdate(ctx context.Context, filterQuery bson.M, updateQuery bson.M) (TData, error) {
+4 -4
View File
@@ -10,8 +10,8 @@ import (
"git.blackforestbytes.com/BlackForestBytes/goext/rfctime" "git.blackforestbytes.com/BlackForestBytes/goext/rfctime"
"git.blackforestbytes.com/BlackForestBytes/goext/timeext" "git.blackforestbytes.com/BlackForestBytes/goext/timeext"
"git.blackforestbytes.com/BlackForestBytes/goext/tst" "git.blackforestbytes.com/BlackForestBytes/goext/tst"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/v2/mongo"
) )
func TestReflectionGetFieldType(t *testing.T) { func TestReflectionGetFieldType(t *testing.T) {
@@ -235,8 +235,8 @@ func TestReflectionGetFieldValueAsTokenString(t *testing.T) {
func TestReflectionWithInterface(t *testing.T) { func TestReflectionWithInterface(t *testing.T) {
type TestData struct { type TestData struct {
ID primitive.ObjectID `bson:"_id"` ID bson.ObjectID `bson:"_id"`
CDate time.Time `bson:"cdate"` CDate time.Time `bson:"cdate"`
} }
type TestInterface interface { type TestInterface interface {
+4 -3
View File
@@ -1,11 +1,12 @@
package wpdf package wpdf
import ( import (
"regexp"
"strconv"
"git.blackforestbytes.com/BlackForestBytes/goext/exerr" "git.blackforestbytes.com/BlackForestBytes/goext/exerr"
"git.blackforestbytes.com/BlackForestBytes/goext/langext" "git.blackforestbytes.com/BlackForestBytes/goext/langext"
"git.blackforestbytes.com/BlackForestBytes/goext/rext" "git.blackforestbytes.com/BlackForestBytes/goext/rext"
"regexp"
"strconv"
) )
// Column specifier: // Column specifier:
@@ -298,7 +299,7 @@ func (b *TableBuilder) calculateColumns() []float64 {
if remainingWidth > 0.01 { if remainingWidth > 0.01 {
rmSub := 0.0 rmSub := 0.0
for i, _ := range columnDef { for i := range columnDef {
if frColumnWeights[i] != 0 { if frColumnWeights[i] != 0 {
addW := (remainingWidth / float64(frColumnWidthCount)) * frColumnWeights[i] addW := (remainingWidth / float64(frColumnWidthCount)) * frColumnWeights[i]
rmSub += addW rmSub += addW