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

76 lines
1.8 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{}) 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 := query.Compose(filters...)
zeroElem := reflect.Zero(targetSliceElemT)
hasPreloader, _ := composed.Preloader()
6 years ago
var result *mongox.Cursor
var err error
6 years ago
if hasPreloader {
result, err = d.createAggregateLoad(zeroElem.Interface(), composed)
} else {
result, err = d.createSimpleLoad(zeroElem.Interface(), composed)
}
6 years ago
if err != nil {
return fmt.Errorf("can't create find result: %w", err)
6 years ago
}
var i int
for i = 0; result.Next(d.Context()); {
6 years ago
if targetSliceV.Len() == i {
elem := reflect.New(targetSliceElemT.Elem())
if err = result.Decode(elem.Interface()); err == nil {
targetSliceV = reflect.Append(targetSliceV, elem)
} else {
continue
6 years ago
}
} else {
elem := targetSliceV.Index(i).Interface()
base.Reset(elem)
if err = result.Decode(elem); err != nil {
continue
}
6 years ago
}
i++
6 years ago
}
targetSliceV = targetSliceV.Slice(0, i)
targetV.Elem().Set(targetSliceV)
return result.Close(d.Context())
6 years ago
}