-
Notifications
You must be signed in to change notification settings - Fork 5
/
query.go
122 lines (98 loc) · 2.41 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
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
111
112
113
114
115
116
117
118
119
120
121
122
package sqlDB
import (
"context"
"database/sql"
"errors"
"github.com/colibri-project-io/colibri-sdk-go/pkg/database/cacheDB"
)
// Query struct
type Query[T any] struct {
ctx context.Context
cache *cacheDB.Cache[T]
query string
args []any
}
// NewQuery create a new pointer to Query struct
func NewQuery[T any](ctx context.Context, query string, params ...any) *Query[T] {
return &Query[T]{ctx, nil, query, params}
}
// NewCachedQuery create a new pointer to Query struct with cache
func NewCachedQuery[T any](ctx context.Context, cache *cacheDB.Cache[T], query string, params ...any) (q *Query[T]) {
return &Query[T]{ctx, cache, query, params}
}
// Many returns a slice of T value
func (q *Query[T]) Many() ([]T, error) {
if err := q.validate(); err != nil {
return nil, err
}
if q.cache == nil {
return q.fetchMany()
}
result, err := q.cache.Many(q.ctx)
if err != nil {
return q.fetchMany()
}
return result, nil
}
func (q *Query[T]) fetchMany() ([]T, error) {
rows, err := q.queryContext()
if err != nil {
return nil, err
}
defer closer(rows)
list, err := getDataList[T](rows)
if err != nil {
return nil, err
}
if q.cache != nil {
q.cache.Set(q.ctx, list)
}
return list, nil
}
// One return a pointer of T value
func (q *Query[T]) One() (*T, error) {
if err := q.validate(); err != nil {
return nil, err
}
if q.cache == nil {
return q.fetchOne()
}
result, err := q.cache.One(q.ctx)
if err != nil {
return q.fetchOne()
}
return result, nil
}
func (q *Query[T]) fetchOne() (*T, error) {
model := new(T)
if err := q.queryRowContext().Scan(reflectCols(model)...); err != nil && err != sql.ErrNoRows {
return nil, err
} else if err == sql.ErrNoRows {
return nil, nil
}
if q.cache != nil {
q.cache.Set(q.ctx, model)
}
return model, nil
}
func (q *Query[T]) validate() error {
if instance == nil {
return errors.New(db_not_initialized_error)
}
if q.query == "" {
return errors.New(query_is_empty_error)
}
return nil
}
func (q *Query[T]) queryContext() (*sql.Rows, error) {
if tx := q.ctx.Value(SqlTxContext); tx != nil {
return tx.(*sql.Tx).QueryContext(q.ctx, q.query, q.args...)
}
return instance.QueryContext(q.ctx, q.query, q.args...)
}
func (q *Query[T]) queryRowContext() *sql.Row {
if tx := q.ctx.Value(SqlTxContext); tx != nil {
return tx.(*sql.Tx).QueryRowContext(q.ctx, q.query, q.args...)
}
return instance.QueryRowContext(q.ctx, q.query, q.args...)
}