-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquery.go
78 lines (65 loc) · 2.29 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
68
69
70
71
72
73
74
75
76
77
78
package sqle
import (
"context"
"fmt"
)
type Errors struct {
items []error
}
func (e *Errors) Error() string {
return fmt.Sprint(e.items)
}
type Query[T any] struct {
db *DB
queryer Queryer[T]
withRotatedTables []string
}
// NewQuery creates a new Query instance.
// It takes a *DB as the first argument and optional QueryOption functions as the rest.
// It returns a pointer to the created Query instance.
func NewQuery[T any](db *DB, options ...QueryOption[T]) *Query[T] {
q := &Query[T]{
db: db,
}
for _, opt := range options {
if opt != nil {
opt(q)
}
}
if q.withRotatedTables == nil {
q.withRotatedTables = []string{""}
}
if q.queryer == nil {
q.queryer = &MapR[T]{
dbs: q.db.dbs,
}
}
return q
}
// First executes the query and returns the first result.
// It takes a context.Context and a *Builder as arguments.
// It returns the result of type T and an error, if any.
func (q *Query[T]) First(ctx context.Context, b *Builder) (T, error) {
return q.queryer.First(ctx, q.withRotatedTables, b)
}
// Count executes the query and returns the number of results.
// It takes a context.Context and a *Builder as arguments.
// It returns the count as an integer and an error, if any.
func (q *Query[T]) Count(ctx context.Context, b *Builder) (int64, error) {
return q.queryer.Count(ctx, q.withRotatedTables, b)
}
// Query executes the query and returns all the results.
// It takes a context.Context, a *Builder, and a comparison function as arguments.
// The comparison function is used to sort the results.
// It returns a slice of results of type T and an error, if any.
func (q *Query[T]) Query(ctx context.Context, b *Builder, less func(i, j T) bool) ([]T, error) {
return q.queryer.Query(ctx, q.withRotatedTables, b, less)
}
// QueryLimit executes the query and returns a limited number of results.
// It takes a context.Context, a *Builder, a comparison function, and a limit as arguments.
// The comparison function is used to sort the results.
// The limit specifies the maximum number of results to return.
// It returns a slice of results of type T and an error, if any.
func (q *Query[T]) QueryLimit(ctx context.Context, b *Builder, less func(i, j T) bool, limit int) ([]T, error) {
return q.queryer.QueryLimit(ctx, q.withRotatedTables, b, less, limit)
}