forked from coze-cloud/clerk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
67 lines (57 loc) 路 1.26 KB
/
query.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
package clerk
import "context"
type Query[T any] struct {
querier Querier[T]
Filters []Filter
Sorting map[string]*Order
Range *Range
}
func NewQuery[T any](querier Querier[T]) *Query[T] {
return &Query[T]{
querier: querier,
Filters: []Filter{},
Sorting: map[string]*Order{},
Range: nil,
}
}
func (q *Query[T]) Where(filter Filter) *Query[T] {
q.Filters = append(q.Filters, filter)
return q
}
func (q *Query[T]) Sort(key string, order ...*Order) *Query[T] {
if len(order) > 0 {
q.Sorting[key] = order[0]
} else {
q.Sorting[key] = NewAscendingOrder()
}
return q
}
func (q *Query[T]) In(rng *Range) *Query[T] {
q.Range = rng
return q
}
func (q *Query[T]) Channel(ctx context.Context) (<-chan T, error) {
return q.querier.ExecuteQuery(ctx, q)
}
func (q *Query[T]) All(ctx context.Context) ([]T, error) {
channel, err := q.Channel(ctx)
if err != nil {
return nil, err
}
var results []T
for result := range channel {
results = append(results, result)
}
return results, nil
}
func (q *Query[T]) Single(ctx context.Context) (T, error) {
channel, err := q.Channel(ctx)
if err != nil {
var empty T
return empty, err
}
return <-channel, nil
}
func (q *Query[T]) Count(ctx context.Context) (int64, error) {
return q.querier.Count(ctx, q)
}