You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mongox-go-driver/mongox/database/loadarray.go

119 lines
2.3 KiB

package database
6 years ago
import (
"fmt"
6 years ago
"reflect"
"github.com/mainnika/mongox-go-driver/v2/mongox"
5 years ago
"github.com/mainnika/mongox-go-driver/v2/mongox/base"
"github.com/mainnika/mongox-go-driver/v2/mongox/query"
6 years ago
)
// LoadArray loads an array of documents from the database by query
func (d *Database) LoadArray(target interface{}, filters ...interface{}) (err error) {
6 years ago
targetV := reflect.ValueOf(target)
targetT := targetV.Type()
targetK := targetV.Kind()
if targetK != reflect.Ptr {
panic(fmt.Errorf("target is not a ptr"))
6 years ago
}
targetSliceV := targetV.Elem()
targetSliceT := targetT.Elem()
if targetSliceT.Kind() != reflect.Slice {
panic(fmt.Errorf("target should be a ptr to a slice"))
6 years ago
}
targetSliceElemT := targetSliceT.Elem()
if targetSliceElemT.Kind() != reflect.Ptr {
panic(fmt.Errorf("target slice should contain ptrs"))
6 years ago
}
composed, err := query.Compose(filters...)
if err != nil {
return
}
zeroElem := reflect.Zero(targetSliceElemT)
_, hasPreloader := composed.Preloader()
ctx := query.WithContext(d.Context(), composed)
6 years ago
var result *mongox.Cursor
var i int
6 years ago
defer func() {
if result != nil {
closerr := result.Close(ctx)
if err == nil {
err = closerr
}
}
invokerr := composed.OnClose().Invoke(ctx, target)
if err == nil {
err = invokerr
}
return
}()
if hasPreloader {
result, err = d.createAggregateLoad(zeroElem.Interface(), composed)
} else {
result, err = d.createSimpleLoad(zeroElem.Interface(), composed)
}
6 years ago
if err != nil {
err = fmt.Errorf("can't create find result: %w", err)
return
6 years ago
}
for i = 0; result.Next(ctx); i++ {
var elem interface{}
if i == targetSliceV.Len() {
value := reflect.New(targetSliceElemT.Elem())
elem = value.Interface()
err = composed.OnCreate().Invoke(ctx, elem)
if err != nil {
return
}
err = result.Decode(elem)
if err != nil {
return
6 years ago
}
targetSliceV = reflect.Append(targetSliceV, value)
} else {
elem = targetSliceV.Index(i).Interface()
if created := base.Reset(elem); created {
err = composed.OnCreate().Invoke(ctx, elem)
}
if err != nil {
return
}
err = result.Decode(elem)
if err != nil {
return
}
6 years ago
}
err = composed.OnDecode().Invoke(ctx, elem)
if err != nil {
return
}
6 years ago
}
targetSliceV = targetSliceV.Slice(0, i)
targetV.Elem().Set(targetSliceV)
return
6 years ago
}