This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
/
find.go
94 lines (76 loc) · 2.63 KB
/
find.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package testingdb
import (
"errors"
"reflect"
"github.com/script-development/RT-CV/db"
"github.com/script-development/RT-CV/db/dbHelpers"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
// FindOne finds one document in the collection of placeInto
// The result can be filtered using filters
// The filters should work equal to MongoDB filters (https://docs.mongodb.com/manual/tutorial/query-documents/)
// tough this might miss features compared to mongoDB's filters
func (c *TestConnection) FindOne(placeInto db.Entry, filters bson.M, optionalOpts ...db.FindOptions) error {
opts := db.FindOptions{}
if len(optionalOpts) > 0 {
opts = optionalOpts[0]
}
queryFilters := filters
if !opts.NoDefaultFilters {
dbHelpers.MergeFilters(placeInto.DefaultFindFilters(), filters)
}
itemsFilter := newFilter(queryFilters)
c.m.Lock()
defer c.m.Unlock()
for _, item := range c.getCollectionFromEntry(placeInto).data {
if !itemsFilter.matches(item) {
continue
}
// We use elem here to get passed the pointer into the underlaying data
placeIntoRefl := reflect.ValueOf(placeInto).Elem()
placeIntoRefl.Set(reflect.ValueOf(item).Elem())
return nil
}
return mongo.ErrNoDocuments
}
// Find finds documents in the collection of the base
// The results can be filtered using filters
// The filters should work equal to MongoDB filters (https://docs.mongodb.com/manual/tutorial/query-documents/)
// tough this might miss features compared to mongoDB's filters
func (c *TestConnection) Find(base db.Entry, results any, filters bson.M, optionalOpts ...db.FindOptions) error {
opts := db.FindOptions{}
if len(optionalOpts) > 0 {
opts = optionalOpts[0]
}
queryFilters := filters
if !opts.NoDefaultFilters {
dbHelpers.MergeFilters(base.DefaultFindFilters(), filters)
}
itemsFilter := newFilter(queryFilters)
c.m.Lock()
defer c.m.Unlock()
resultRefl := reflect.ValueOf(results)
if resultRefl.Kind() != reflect.Ptr {
return errors.New("requires pointer to slice as results argument")
}
resultRefl = resultRefl.Elem()
if resultRefl.Kind() != reflect.Slice {
return errors.New("requires pointer to slice as results argument")
}
resultsSliceContentType := resultRefl.Type().Elem()
resultIsSliceOfPtrs := resultsSliceContentType.Kind() == reflect.Ptr
for _, item := range c.getCollectionFromEntry(base).data {
if !itemsFilter.matches(item) {
continue
}
itemRefl := reflect.ValueOf(item)
if resultIsSliceOfPtrs {
resultRefl = reflect.Append(resultRefl, itemRefl)
} else {
resultRefl = reflect.Append(resultRefl, itemRefl.Elem())
}
}
reflect.ValueOf(results).Elem().Set(resultRefl)
return nil
}