-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
328 lines (300 loc) · 11.6 KB
/
main.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package pbsql
import (
"fmt"
"reflect"
"strings"
"github.com/jmoiron/sqlx"
)
// BuildCountQuery_OLD is deprecated is a convenience wrapper for getting the result count of a query already generated by pbsql
// value based, does not affect the initially supplied query string
func BuildCountQuery_OLD(selectQry string) string {
return "SELECT COUNT(*) as count FROM (" + selectQry + ") as count"
}
// BuildCreateQuery accepts a target table name and a protobuf message and attempts to build a valid SQL insert statement for use
// with sqlx.Named, ignoring any struct fields with default values. Fields must be tagged with `db:""` in order to be
// included in the result string.
func BuildCreateQuery(target string, source interface{}) (string, []interface{}, error) {
t := reflect.ValueOf(source).Elem()
var qb queryBuilder
fmt.Fprintf(&qb.Columns, "INSERT INTO %s (", target)
qb.Values.WriteString("(")
for i := 0; i < t.NumField(); i++ {
field := parseReflection(t, i, target)
if field.value.CanInterface() {
if notDefault(field.typeStr, field.value.Interface()) && field.name != "" {
if i != 0 {
qb.Columns.WriteString(", ")
qb.Values.WriteString(", ")
}
fmt.Fprintf(&qb.Columns, "%s.%s", target, field.name)
fmt.Fprintf(&qb.Values, ":%s", field.name)
}
}
}
qb.Values.WriteString(")")
fmt.Fprintf(&qb.Columns, ") VALUES %s", qb.Values.String())
result := strings.ReplaceAll(qb.Columns.String(), "(, ", "(")
return sqlx.Named(result, source)
}
// BuildDeleteQuery accepts a target table name and a protobuf message and attempts to build a valid SQL
// delete statement by utilizing struct tags to denote information such as database field names and
// whether something is a primary key. If successful, returns a SQL statement in the form of a string,
// a slice of args to interpolate, and a nil error.
//
// This function returns a nullsafe query if nullable struct fields are properly tagged as `nullable:"y"`.
//
// If an IsActive field is detected (is_active), this func returns an update statement that sets is_active to 0,
// otherwise it returns a delete statement
func BuildDeleteQuery(target string, source interface{}) (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(source).Elem()
var builder strings.Builder
if _, hasIsActive := reflectedValue.Type().FieldByName("IsActive"); hasIsActive {
fmt.Fprintf(&builder, "UPDATE %s SET %s.is_active = 0 WHERE ", target, target)
} else {
fmt.Fprintf(&builder, "DELETE FROM %s WHERE ", target)
}
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, target)
if field.isPrimaryKey {
fmt.Fprintf(&builder, "%s.%s = :%s", target, field.name, field.name)
break
}
}
return sqlx.Named(builder.String(), source)
}
// BuildSearchQuery builds a search query
func BuildSearchQuery(target string, source interface{}, searchPhrase string) (string, []interface{}, error) {
var qb queryBuilder
qb.Core.WriteString("SELECT ")
qb.Predicate.WriteString(" WHERE true")
reflectedValue := reflect.ValueOf(source).Elem()
fieldMask := make([]string, 0)
fields := make([]*field, 0)
n := reflectedValue.NumField()
for i := 0; i < n; i++ {
field := parseReflection(reflectedValue, i, target)
if field.selectFunc.ok {
field.shouldIgnore = true
}
fields = append(fields, field)
if field.name != "" && !field.shouldIgnore {
if field.typeStr == "string" && field.value.String() == "" {
fieldMask = append(fieldMask, field.self.Name)
} else if field.value.CanAddr() {
qb.writePredicate(field, fieldMask, andPredicate)
}
} else if field.selectFunc.ok {
qb.writeSelectFunc(field)
}
}
qb.Predicate.WriteString(" AND (")
for i := 0; i < n; i++ {
field := fields[i]
if field.name != "" && !field.shouldIgnore {
qb.writeSelectField(field)
if field.value.CanAddr() {
if field.typeStr == "string" && field.value.String() == "" {
qb.writePredicate(field, fieldMask, orPredicate)
}
}
}
if field.hasForeignKey {
qb.handleForeignKey(field)
}
}
qb.Predicate.WriteString(")")
/* here we choose to use the args returned from BuildReadQuery*/
qry, falseArgs, err := sqlx.Named(qb.getReadResult(target, &reflectedValue), source)
_, altArgs, _ := BuildReadQuery(target, source)
searchArgs := getSearchArgs(len(falseArgs)-len(altArgs), searchPhrase)
return qry, append(altArgs, searchArgs...), err
}
// BuildCountQuery is a convenience wrapper for getting the result count of a query already generated by pbsql
// value based, does not affect the initially supplied query string
func BuildCountQuery(target string, source interface{}, fieldMask ...string) (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(source).Elem()
var qb queryBuilder
qb.Core.WriteString("SELECT COUNT(*) ")
qb.Predicate.WriteString(" WHERE TRUE")
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, target)
if field.value.CanInterface() {
if field.name != "" && field.value.CanAddr() {
qb.writePredicate(field, fieldMask, andPredicate)
}
if field.hasForeignKey {
qb.handleForeignKey(field)
}
}
}
result := qb.getReadResult(target, &reflectedValue)
return sqlx.Named(result, source)
}
// BuildReadQuery accepts a target table name and a protobuf message and attempts to build a valid SQL select statement,
// ignoring any struct fields with default values when writing predicates. Fields must be tagged with `db:""` in order to be
// included in the result string.
//
// Returns a SQL statement as a string, a slice of args to interpolate, and an error
func BuildReadQuery(target string, source interface{}, fieldMask ...string) (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(source).Elem()
var qb queryBuilder
qb.Core.WriteString("SELECT ")
qb.Predicate.WriteString(" WHERE true")
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, target)
if field.name != "" {
if !field.shouldIgnore && !field.selectFunc.ok {
qb.writeSelectField(field)
if field.value.CanAddr() {
qb.writePredicate(field, fieldMask, andPredicate)
}
} else if field.selectFunc.ok {
qb.writeSelectFunc(field)
} else if field.isMultiValue && field.value.CanAddr() {
qb.writePredicate(field, fieldMask, andPredicate)
}
}
if field.hasForeignKey {
qb.handleForeignKey(field)
}
}
qb.handleDateRange(target, &reflectedValue)
result := qb.getReadResult(target, &reflectedValue)
return sqlx.Named(result, source)
}
// BuildReadQueryWithNotList accepts a target table name and a protobuf message and attempts to build a valid SQL select statement,
// ignoring any struct fields with default values when writing predicates. Fields must be tagged with `db:""` in order to be
// included in the result string.
//
// Returns a SQL statement as a string, a slice of args to interpolate, and an error
func BuildReadQueryWithNotList(target string, source interface{}, notList []string, fieldMask ...string) (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(source).Elem()
var qb queryBuilder
qb.Core.WriteString("SELECT ")
qb.Predicate.WriteString(" WHERE true")
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, target)
if field.name != "" {
if !field.shouldIgnore && !field.selectFunc.ok {
qb.writeSelectField(field)
if field.value.CanAddr() {
if findInMask(notList, field.self.Name) {
qb.writeNotPredicate(field, notList, andPredicate)
} else {
qb.writePredicate(field, fieldMask, andPredicate)
}
}
} else if field.selectFunc.ok {
qb.writeSelectFunc(field)
} else if field.isMultiValue && field.value.CanAddr() {
if findInMask(notList, field.self.Name) {
qb.writeNotPredicate(field, notList, andPredicate)
} else {
qb.writePredicate(field, fieldMask, andPredicate)
}
}
}
if field.hasForeignKey {
qb.handleForeignKey(field)
}
}
qb.handleDateRange(target, &reflectedValue)
result := qb.getReadResult(target, &reflectedValue)
return sqlx.Named(result, source)
}
type Query struct {
Target string
Source interface{}
NotList []string
FieldMask []string
Collate bool
}
func (q *Query) BuildRead() (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(q.Source).Elem()
var qb queryBuilder
qb.Core.WriteString("SELECT ")
qb.Predicate.WriteString(" WHERE true")
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, q.Target)
if field.name != "" {
if !field.shouldIgnore && !field.selectFunc.ok {
qb.writeSelectField(field)
if field.value.CanAddr() {
if findInMask(q.NotList, field.self.Name) {
qb.writeNotPredicate(field, q.NotList, andPredicate)
} else {
qb.writePredicate(field, q.FieldMask, andPredicate)
}
}
} else if field.selectFunc.ok {
qb.writeSelectFunc(field)
} else if field.isMultiValue && field.value.CanAddr() {
if findInMask(q.NotList, field.self.Name) {
qb.writeNotPredicate(field, q.NotList, andPredicate)
} else {
qb.writePredicate(field, q.FieldMask, andPredicate)
}
}
}
if field.hasForeignKey {
qb.handleForeignKey(field)
}
}
qb.handleDateRange(q.Target, &reflectedValue)
result := qb.getReadResult(q.Target, &reflectedValue)
return sqlx.Named(result, q.Source)
}
// BuildUpdateQuery accepts a target table name `target`, a struct `source`, and a list of struct fields `fieldMask`
// and attempts to build a valid sql update statement for use with sqlx.Named, ignoring any struct fields not present
// in `fieldMask`. Struct fields must also be tagged with `db:""`, and the primary key should be tagged as
// `primary_key` otherwise this function will return an invalid query
func BuildUpdateQuery(target string, source interface{}, fieldMask []string) (string, []interface{}, error) {
reflectedValue := reflect.ValueOf(source).Elem()
var qb queryBuilder
fmt.Fprintf(&qb.Core, "UPDATE %s SET ", target)
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, target)
if field.value.CanInterface() && field.name != "" {
if field.isPrimaryKey {
fmt.Fprintf(&qb.Predicate, "WHERE %s.%s = :%s", target, field.name, field.name)
} else if findInMask(fieldMask, field.self.Name) && !field.shouldIgnore && field.value.CanInterface() {
fmt.Fprintf(&qb.Core, "%s.%s = :%s, ", target, field.name, field.name)
}
}
}
return sqlx.Named(qb.getUpdateResult(), source)
}
// BuildRelatedReadQuery can be used to quickly build queries for many to one relationships
// This method is still experimental
func BuildRelatedReadQuery(source interface{}, foreignKey string, foreignValue interface{}) string {
var qb queryBuilder
reflectedValue := reflect.ValueOf(source).Elem()
for i := 0; i < reflectedValue.NumField(); i++ {
field := parseReflection(reflectedValue, i, "")
foreignKeyTag := field.self.Tag.Get("foreign_key")
foreignTable := field.self.Tag.Get("foreign_table")
localName := field.self.Tag.Get("local_name")
if foreignKeyTag == foreignKey && foreignTable != "" && localName != "" {
related := reflect.Indirect(field.value)
fmt.Fprintf(&qb.Core, "SELECT ")
if related.CanAddr() {
for j := 0; j < related.NumField(); j++ {
f := parseReflection(related, j, foreignTable)
if f.name != "" && f.value.CanInterface() {
qb.writeSelectField(f)
}
}
fmt.Fprintf(
&qb.Core,
"%sFROM %s where %s.%s = %v",
qb.Fields.String(),
foreignTable,
foreignTable,
foreignKey,
foreignValue,
)
}
}
}
return strings.Replace(qb.Core.String(), ", FROM", " FROM", 1)
}