query.go
6.6 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package starrocks
import (
"database/sql"
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
"gorm.io/gorm"
"reflect"
"strings"
)
var AssertString = utils.AssertString
func Query(params QueryOptions, queryFunc func(params QueryOptions) (*sql.Rows, error)) (*domain.DataTable, error) {
rows, err := queryFunc(params)
if err != nil {
return nil, err
}
defer rows.Close()
dataTable := &domain.DataTable{}
dataTable.Data, err = ScanRows(rows)
//rows.Columns()
return dataTable, err
}
type QueryOptions struct {
Table *domain.Table
TableName string
Select []*domain.Field
Where []Condition
Offset int
Limit int
Context *domain.Context
}
func (o *QueryOptions) SetOffsetLimit(pageNumber, pageSize int) {
if pageNumber == 0 {
pageNumber = 1
}
if pageSize == 0 {
pageSize = 20
}
o.Offset = (pageNumber - 1) * pageSize
o.Limit = pageSize
}
func (o *QueryOptions) SetCondition(conditions []domain.Condition) *QueryOptions {
for _, c := range conditions {
o.Where = append(o.Where, Condition{
Condition: c,
})
}
return o
}
func (o *QueryOptions) SetDefaultOrder() *QueryOptions {
hasOrder := false
for _, c := range o.Where {
if len(c.Order) > 0 {
hasOrder = true
}
}
// 没有排序的加一个排序,才能分页
if !hasOrder {
if o.Table != nil {
o.Where = append(o.Where, Condition{
Condition: domain.Condition{
Field: o.Table.PK,
Order: "ASC",
},
})
return o
}
o.Where = append(o.Where, Condition{
Condition: domain.Condition{
Field: domain.PK(),
Order: "ASC",
},
})
}
return o
}
type Condition struct {
domain.Condition
Distinct bool
DisableFormat bool
}
func (c Condition) SetWhere(params QueryOptions, q *gorm.DB) {
if len(c.Like) > 0 {
q.Where(fmt.Sprintf("%v like '%%%v%%'", c.FormatIfNull(params, c.Field), c.Like))
}
if len(c.In) > 0 {
q.Where(fmt.Sprintf("%v in %v", c.FormatIfNull(params, c.Field), c.InArgs(c.In)))
}
if len(c.Ex) > 0 {
in := c.InArgs(c.Ex)
q.Where(fmt.Sprintf("%v not in %v", c.FormatIfNull(params, c.Field), in))
}
if len(c.Range) > 0 {
for _, item := range c.Range {
if item.Op == "" {
continue
}
opVal, ok := opMap[item.Op]
if !ok {
continue
}
val, err := domain.ValueToType(AssertString(item.Val), c.Field.SQLType)
if err != nil {
log.Logger.Error(err.Error())
continue
}
q.Where(fmt.Sprintf("%s %s %s",
c.FormatIfNull(params, c.Field),
opVal,
c.formatByOp(item.Op, val),
))
}
}
if c.Distinct {
q.Distinct(c.Field.SQLName)
}
if len(c.Order) > 0 {
q.Order(fmt.Sprintf("%v %v", c.Field.SQLName, c.Order))
}
}
func (c Condition) FormatIfNull(params QueryOptions, f *domain.Field) string {
if params.Table != nil && params.Table.TableType == domain.ObjectDBTable {
return f.SQLName
}
if domain.SQLType(f.SQLType).IsString() {
return fmt.Sprintf("ifnull(%s,'')", f.SQLName)
}
return f.SQLName
}
var opMap = map[string]string{
"=": "=",
">": ">",
"<": "<",
">=": ">=",
"<=": "<=",
"<>": "<>",
"like": "like",
"not like": "not like",
}
func (c Condition) formatByOp(op string, val interface{}) string {
if op == "like" || op == "not like" {
return fmt.Sprintf("'%%%s%%'", AssertString(val))
}
return c.Arg(val)
}
func (c Condition) InArgs(args interface{}) string {
bytes := make([]byte, 0)
bytes = appendIn(bytes, reflect.ValueOf(args))
return string(bytes)
}
func (c Condition) Arg(args interface{}) string {
bytes := make([]byte, 0)
v := reflect.ValueOf(args)
bytes = appendValue(bytes, v)
return string(bytes)
}
func appendIn(b []byte, slice reflect.Value) []byte {
sliceLen := slice.Len()
b = append(b, '(')
for i := 0; i < sliceLen; i++ {
if i > 0 {
b = append(b, ',')
}
elem := slice.Index(i)
if elem.Kind() == reflect.Interface {
elem = elem.Elem()
}
if elem.Kind() == reflect.Slice {
//b = appendIn(b, elem)
} else {
b = appendValue(b, elem)
}
}
b = append(b, ')')
return b
}
func appendValue(b []byte, v reflect.Value) []byte {
if v.Kind() == reflect.Ptr && v.IsNil() {
return append(b, "NULL"...)
}
if v.Kind() == reflect.Int || v.Kind() == reflect.Int64 || v.Kind() == reflect.Float64 {
return append(b, []byte(AssertString(v.Interface()))...)
}
b = append(b, []byte("'")...)
b = append(b, []byte(AssertString(v.Interface()))...)
b = append(b, []byte("'")...)
return b
}
func DefaultQueryFunc(params QueryOptions) (*sql.Rows, error) {
query := DB.Table(params.TableName)
rows, err := query.Rows()
if err != nil {
return nil, err
}
return rows, nil
}
func WrapQueryFuncWithDB(db *gorm.DB) func(QueryOptions) (*sql.Rows, error) {
return func(params QueryOptions) (*sql.Rows, error) {
query := db.Table(params.TableName)
queryWithoutLimitOffset(query, params)
if params.Offset > 0 {
query.Offset(params.Offset)
}
if params.Limit > 0 {
query.Limit(params.Limit)
}
if params.Context != nil {
query.Where(fmt.Sprintf("context->>'companyId'='%v'", params.Context.CompanyId))
}
rows, err := query.Rows()
if err != nil {
return nil, err
}
return rows, nil
}
}
func SetTable(query *gorm.DB, tableName string) {
query.Statement.Table = tableName
}
func queryWithoutLimitOffset(query *gorm.DB, params QueryOptions) {
if len(params.Select) > 0 {
fields := make([]string, 0)
for _, f := range params.Select {
if f.Flag == domain.ManualField {
fields = append(fields, "'' "+f.SQLName)
continue
}
fields = append(fields, f.SQLName)
}
query.Select(strings.Join(fields, ","))
}
if len(params.Where) > 0 {
for _, w := range params.Where {
if w.Field.Flag == domain.ManualField {
continue
}
w.SetWhere(params, query)
}
}
}
func QueryCount(params QueryOptions) (int64, error) {
var total int64
query := DB.Table(params.TableName)
queryWithoutLimitOffset(query, params)
query.Count(&total)
return total, query.Error
}
func WrapQueryCountWithDB(params QueryOptions, db *gorm.DB) func() (int64, error) {
return func() (int64, error) {
var total int64
query := db.Table(params.TableName)
queryWithoutLimitOffset(query, params)
if params.Context != nil {
query.Where(fmt.Sprintf("context->>'companyId'='%v'", params.Context.CompanyId))
}
query.Count(&total)
return total, query.Error
}
}
func ArrayInterfaceToString(args []interface{}) []string {
result := make([]string, 0)
for _, arg := range args {
result = append(result, AssertString(arg))
}
return result
}