query.gno
1.71 Kb · 71 lines
1package datasource
2
3import "gno.land/p/nt/avl/v0"
4
5// DefaultQueryRecords defines the default number of records returned by queries.
6const DefaultQueryRecords = 50
7
8type (
9 // QueryOption configures datasource queries.
10 QueryOption func(*Query)
11
12 // Query contains datasource query options.
13 Query struct {
14 // Offset of the first record to return during iteration.
15 Offset int
16
17 // Count contains the number to records that query should return.
18 Count int
19
20 // Tag contains a tag to use as filter for the records.
21 Tag string
22
23 // Filters contains optional query filters by field value.
24 Filters avl.Tree
25 }
26)
27
28// WithOffset configures query to return records starting from an offset.
29func WithOffset(offset int) QueryOption {
30 return func(q *Query) {
31 q.Offset = offset
32 }
33}
34
35// WithCount configures the number of records that query returns.
36func WithCount(count int) QueryOption {
37 return func(q *Query) {
38 if count < 1 {
39 count = DefaultQueryRecords
40 }
41 q.Count = count
42 }
43}
44
45// ByTag configures query to filter by tag.
46func ByTag(tag string) QueryOption {
47 return func(q *Query) {
48 q.Tag = tag
49 }
50}
51
52// WithFilter assigns a new filter argument to a query.
53// This option can be used multiple times if more than one
54// filter has to be given to the query.
55func WithFilter(field string, value any) QueryOption {
56 return func(q *Query) {
57 q.Filters.Set(field, value)
58 }
59}
60
61// NewQuery creates a new datasource query.
62func NewQuery(options ...QueryOption) Query {
63 // Construct a fresh Query in the caller's realm; copying from a
64 // package-level default would propagate the /p/-readonly taint
65 // and break the apply(&q) options below.
66 q := Query{Count: DefaultQueryRecords}
67 for _, apply := range options {
68 apply(&q)
69 }
70 return q
71}