-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.go
More file actions
263 lines (238 loc) · 6.5 KB
/
select.go
File metadata and controls
263 lines (238 loc) · 6.5 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package ormx
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"github.com/cloudfly/ormx/cache"
sb "github.com/huandu/go-sqlbuilder"
"github.com/rs/zerolog"
)
func GetByID(ctx context.Context, dst any, id any, opt *Option) error {
table := TableName(dst, opt)
if !opt.fromMaster {
// Not reading data from the primary database indicates that some delay is tolerable.
// Attempt to read from the local cache.
if v, ok := cache.Get(table, id); ok {
if content, ok := v.([]byte); ok {
if err := json.Unmarshal(content, dst); err == nil {
return nil
} else {
// Deserialization error indicates that the data is unusable. Delete it directly.
cache.Remove(table, id)
}
}
}
}
b, err := NewSelectBuilderFromStruct(dst, opt)
if err != nil {
return fmt.Errorf("create select builder error:%w", err)
}
b = b.Where(WhereFrom(&b.Cond, id, nil, opt)...)
var (
statement string
args []any
)
statement, args = Build(ctx, b)
if opt.tx != nil {
err = GetTx(ctx, opt.tx, dst, statement, args...)
} else {
err = Get(ctx, dst, statement, args...)
}
if err != nil {
return err
}
content, err := json.Marshal(dst)
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Str("query", statement).Any("args", args).Msg("Failed to marshal data for cacheing")
// 忽略序列化错误,顶多就是无法cache,无关紧要
return nil
}
cache.Set(time.Second*10, table, id, content)
return nil
}
// GetWhere 使用自定义条件跟新数据
func GetWhere(ctx context.Context, dst any, filter any, opt *Option) error {
builder, err := NewSelectBuilderFromStruct(dst, opt)
if err != nil {
return fmt.Errorf("new select builder error: %w", err)
}
if len(opt.fields) > 0 {
builder = builder.Select(opt.fields...)
}
builder = builder.Where(WhereFrom(&builder.Cond, filter, nil, opt)...)
sql, args := Build(ctx, builder)
if opt.tx != nil {
err = GetTx(ctx, opt.tx, dst, sql, args...)
} else {
err = Get(ctx, dst, sql, args...)
}
return err
}
// GetWhere 使用自定义条件跟新数据
func SelectWhere(ctx context.Context, dst any, filter any, opt *Option) error {
builder, err := NewSelectBuilderFromStruct(dst, opt)
if err != nil {
return fmt.Errorf("new select builder error: %w", err)
}
if len(opt.fields) > 0 {
builder = builder.Select(opt.fields...)
}
builder = builder.Where(WhereFrom(&builder.Cond, filter, nil, opt)...)
if len(opt.sorts) > 0 {
orderByCols := make([]string, 0, 8)
for _, col := range opt.sorts {
if col == "" {
continue
}
if col[0] == '-' {
orderByCols = append(orderByCols, strings.TrimLeft(col, "-")+" DESC")
} else {
orderByCols = append(orderByCols, col+" ASC")
}
}
builder = builder.OrderBy(orderByCols...)
}
if opt.page > 0 && opt.pageSize > 0 {
builder = builder.Limit(opt.pageSize).Offset((opt.page - 1) * opt.pageSize)
}
sql, args := Build(ctx, builder)
if opt.fromMaster {
ctx = FromMaster(ctx)
}
if opt.tx != nil {
err = SelectTx(ctx, opt.tx, dst, sql, args...)
} else {
err = Select(ctx, dst, sql, args...)
}
return err
}
// Count select the count of rows in table which match the filter condition
func Count(ctx context.Context, filter any, opt *Option) (int64, error) {
total := sql.NullInt64{}
table := TableName(nil, opt)
b := sb.NewSelectBuilder().Select("COUNT(1) as total").From(table)
b = b.Where(WhereFrom(&b.Cond, filter, nil, opt)...)
sql, args := Build(ctx, b)
if opt.fromMaster {
ctx = FromMaster(ctx)
}
var err error
if opt.tx != nil {
err = GetTx(ctx, opt.tx, &total, sql, args...)
} else {
err = Get(ctx, &total, sql, args...)
}
if IsNotFound(err) {
err = nil
}
return total.Int64, err
}
// Count select the count of rows in table which match the filter condition
func CountBy(ctx context.Context, dst any, filter any, group []string, opt *Option) error {
cols := []string{"COUNT(1) as _total"}
if len(group) > 0 {
cols = append(cols, group...)
}
table := TableName(nil, opt)
b := sb.NewSelectBuilder().Select(cols...).From(table)
b = b.Where(WhereFrom(&b.Cond, filter, nil, opt)...)
if len(group) > 0 {
b = b.GroupBy(group...)
}
if opt.fromMaster {
ctx = FromMaster(ctx)
}
sql, args := Build(ctx, b)
var err error
if opt.tx != nil {
err = SelectTx(ctx, opt.tx, dst, sql, args...)
} else {
err = Select(ctx, dst, sql, args...)
}
if IsNotFound(err) {
err = nil
}
return err
}
// Distinct fetch distinct values of the column in table
func Distinct(ctx context.Context, column string, filter any, opt *Option) ([]any, error) {
table := TableName(nil, opt)
builder := sb.NewSelectBuilder().From(table)
builder = builder.Select(fmt.Sprintf("DISTINCT(%s) as %s", sb.Escape(column), sb.Escape(column)))
conds := WhereFrom(&builder.Cond, filter, nil, opt)
builder = builder.Where(conds...)
sql, args := Build(ctx, builder)
if opt.fromMaster {
ctx = FromMaster(ctx)
}
var (
data = []any{}
err error
)
if opt.tx != nil {
err = SelectTx(ctx, opt.tx, &data, sql, args...)
} else {
err = Select(ctx, &data, sql, args...)
}
if err != nil {
return nil, fmt.Errorf("select error: %w", err)
}
return data, nil
}
// Exist return true if the at least one row found in table by using where condition
func Exist(ctx context.Context, filter any, opt *Option) (bool, error) {
n := sql.NullInt64{}
table := TableName(nil, opt)
b := sb.NewSelectBuilder().Select("1").From(table).Limit(1)
b = b.Where(WhereFrom(&b.Cond, filter, nil, opt)...)
if opt.fromMaster {
ctx = FromMaster(ctx)
}
statement, args := Build(ctx, b)
var err error
if opt.tx != nil {
err = GetTx(ctx, opt.tx, &n, statement, args...)
} else {
err = Get(ctx, &n, statement, args...)
}
if err != nil {
if IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
// NewSelectBuilderFromStruct create select sql builder by data
func NewSelectBuilderFromStruct(data any, opt *Option) (*sb.SelectBuilder, error) {
table := TableName(data, opt)
b := sb.NewSelectBuilder().From(table)
if data == nil {
b = b.Select("*")
return b, nil
}
t := dereferencedElemType(reflect.TypeOf(data))
cols := make([]string, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
fieldType := t.Field(i)
name, after := colNameFromTag(fieldType, opt.tagName, data)
if name == "" {
continue
}
opts := ParseOptionStr(after)
if optv, ok := opts["select"]; ok && (optv == "-" || optv == "false") {
continue
}
cols = append(cols, name)
}
if len(cols) == 0 {
b = b.Select("*")
} else {
b = b.Select(cols...)
}
return b, nil
}