forked from coze-cloud/clerk
/
index_querier.go
110 lines (93 loc) 路 2.21 KB
/
index_querier.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package mongodb
import (
"context"
"github.com/Becklyn/clerk/v4"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type indexQuerier struct {
connection *Connection
collection *clerk.Collection
}
func newIndexQuerier(connection *Connection, collection *clerk.Collection) *indexQuerier {
return &indexQuerier{
connection: connection,
collection: collection,
}
}
func (q *indexQuerier) Count(
ctx context.Context,
query *clerk.Query[*clerk.Index],
) (int64, error) {
queryCtx, cancel := q.connection.config.GetContext(ctx)
defer cancel()
cursor, err := q.connection.client.
Database(q.collection.Database.Name).
Collection(q.collection.Name).
Indexes().
List(queryCtx)
if err != nil {
return 0, err
}
var indices []*clerk.Index
err = cursor.All(queryCtx, &indices)
return int64(len(indices)), err
}
func (q *indexQuerier) ExecuteQuery(
ctx context.Context,
query *clerk.Query[*clerk.Index],
) (<-chan *clerk.Index, error) {
queryCtx, cancel := q.connection.config.GetContext(ctx)
defer cancel()
cursor, err := q.connection.client.
Database(q.collection.Database.Name).
Collection(q.collection.Name).
Indexes().
List(queryCtx)
if err != nil {
return nil, err
}
channel := make(chan *clerk.Index)
go func() {
defer cursor.Close(queryCtx)
defer close(channel)
for cursor.Next(queryCtx) {
model := primitive.D{}
if err := cursor.Decode(&model); err != nil {
return
}
indx := &clerk.Index{}
for _, kv := range model {
switch kv.Key {
case "name":
indx.Name = kv.Value.(string)
case "key":
fields := []*clerk.Field{}
for _, field := range kv.Value.(primitive.D) {
fields = append(fields, &clerk.Field{
Key: field.Key,
Type: func() clerk.FieldType {
switch field.Value {
case 1:
return clerk.FieldTypeAscending
case -1:
return clerk.FieldTypeDescending
case "text":
return clerk.FieldTypeText
}
return clerk.FieldTypeAscending
}(),
})
}
indx.Fields = fields
case "unique":
indx.IsUnique = kv.Value.(bool)
}
}
if indx.Name == "_id_" {
indx.IsUnique = true
}
channel <- indx
}
}()
return channel, nil
}