Skip to content

Commit aab046c

Browse files
committed
Refactor reflect
1 parent 8afdabd commit aab046c

File tree

6 files changed

+47
-47
lines changed

6 files changed

+47
-47
lines changed

appr_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func NewApprHandlerWithKeysAndLog(apprService ApprService, modelType reflect.Typ
4343
offset = 1
4444
}
4545
if idNames == nil || len(idNames) == 0 {
46-
idNames = getListFieldsTagJson(modelType)
46+
idNames = getJsonPrimaryKeys(modelType)
4747
}
4848
indexes := getIndexes(modelType)
4949
var resource, action1, action2 string

appr_list_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ func NewApprListHandler(apprListService ApprListService, modelType reflect.Type,
2323

2424
func NewApprListHandlerWithKeys(apprListService ApprListService, modelType reflect.Type, logError func(context.Context, string), idNames []string, writeLog func(context.Context, string, string, bool, string) error, options ...string) *ApprListHandler {
2525
if len(idNames) == 0 {
26-
idNames = getListFieldsTagJson(modelType)
26+
idNames = getJsonPrimaryKeys(modelType)
2727
}
2828
var resource, action1, action2 string
2929
if len(options) > 0 && len(options[0]) > 0 {

diff_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func NewDiffHandlerWithKeys(diffService DiffService, modelType reflect.Type, log
3636
offset = options[0]
3737
}
3838
if idNames == nil || len(idNames) == 0 {
39-
idNames = getListFieldsTagJson(modelType)
39+
idNames = getJsonPrimaryKeys(modelType)
4040
}
4141
indexes := getIndexes(modelType)
4242
var resource, action string

diff_list_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func NewDiffListHandler(diffListService DiffListService, modelType reflect.Type,
2424
}
2525
func NewDiffListHandlerWithKeys(diffListService DiffListService, modelType reflect.Type, logError func(context.Context, string), idNames []string, config *DiffModelConfig, writeLog func(context.Context, string, string, bool, string) error) *DiffListHandler {
2626
if idNames == nil || len(idNames) == 0 {
27-
idNames = getListFieldsTagJson(modelType)
27+
idNames = getJsonPrimaryKeys(modelType)
2828
}
2929
modelTypeId := newModelTypeID(modelType, idNames)
3030
var resource, action string

http_util.go

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,25 @@ import (
1313

1414
const internalServerError = "Internal Server Error"
1515

16+
func getJsonPrimaryKeys(modelType reflect.Type) []string {
17+
numField := modelType.NumField()
18+
var idFields []string
19+
for i := 0; i < numField; i++ {
20+
field := modelType.Field(i)
21+
ormTag := field.Tag.Get("gorm")
22+
tags := strings.Split(ormTag, ";")
23+
for _, tag := range tags {
24+
if strings.Compare(strings.TrimSpace(tag), "primary_key") == 0 {
25+
jsonTag := field.Tag.Get("json")
26+
tags1 := strings.Split(jsonTag, ",")
27+
if len(tags1) > 0 && tags1[0] != "-" {
28+
idFields = append(idFields, tags1[0])
29+
}
30+
}
31+
}
32+
}
33+
return idFields
34+
}
1635
func buildResourceName(s string) string {
1736
s2 := strings.ToLower(s)
1837
s3 := ""
@@ -104,57 +123,38 @@ func buildIds(r *http.Request, modelType reflect.Type, idNames []string) (interf
104123
if len(idNames) > 1 {
105124
return newModels(r.Body, modelType)
106125
} else if len(idNames) == 1 {
107-
modelTypeKey := getTypeFieldByJsonName(modelType, idNames[0])
126+
modelTypeKey := getFieldType(modelType, idNames[0])
108127
if modelTypeKey != nil {
109128
return newModels(r.Body, modelTypeKey)
110129
}
111130
}
112131
return nil, errors.New("invalid model type: no id of this model type")
113132
}
114-
func newModels(body interface{}, modelType reflect.Type) (out interface{}, err error) {
115-
req := reflect.New(reflect.SliceOf(modelType)).Interface()
116-
if body != nil {
117-
switch dec := body.(type) {
118-
case io.Reader:
119-
err := json.NewDecoder(dec).Decode(&req)
120-
if err != nil {
121-
return nil, err
122-
}
123-
return req, nil
124-
}
125-
}
126-
return nil, nil
127-
}
128-
func getTypeFieldByJsonName(modelType reflect.Type, jsonname string) reflect.Type {
133+
func getFieldType(modelType reflect.Type, jsonName string) reflect.Type {
129134
numField := modelType.NumField()
130135
for i := 0; i < numField; i++ {
131136
field := modelType.Field(i)
132137
if tag, ok := field.Tag.Lookup("json"); ok {
133-
if strings.Split(tag, ",")[0] == jsonname {
138+
if strings.Split(tag, ",")[0] == jsonName {
134139
return field.Type
135140
}
136141
}
137142
}
138143
return nil
139144
}
140-
func getListFieldsTagJson(modelType reflect.Type) []string {
141-
numField := modelType.NumField()
142-
var idFields []string
143-
for i := 0; i < numField; i++ {
144-
field := modelType.Field(i)
145-
ormTag := field.Tag.Get("gorm")
146-
tags := strings.Split(ormTag, ";")
147-
for _, tag := range tags {
148-
if strings.Compare(strings.TrimSpace(tag), "primary_key") == 0 {
149-
jsonTag := field.Tag.Get("json")
150-
tags1 := strings.Split(jsonTag, ",")
151-
if len(tags1) > 0 && tags1[0] != "-" {
152-
idFields = append(idFields, tags1[0])
153-
}
145+
func newModels(body interface{}, modelType reflect.Type) (out interface{}, err error) {
146+
req := reflect.New(reflect.SliceOf(modelType)).Interface()
147+
if body != nil {
148+
switch dec := body.(type) {
149+
case io.Reader:
150+
err := json.NewDecoder(dec).Decode(&req)
151+
if err != nil {
152+
return nil, err
154153
}
154+
return req, nil
155155
}
156156
}
157-
return idFields
157+
return nil, nil
158158
}
159159
func getIndexes(modelType reflect.Type) map[string]int {
160160
numField := modelType.NumField()

sql_diff.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ type SqlHistoryWriter struct {
7474
}
7575

7676
func NewSqlDiffReader(db *sql.DB, table string, entity string, entityType string, idNames []string, config DiffConfig, keyBuilder KeyBuilder, options...func(int) string) *SqlDiffReader {
77-
columnSelect := BuildQueryColumn(config)
77+
columnSelect := buildQueryColumns(config)
7878
driver := getDriver(db)
7979
var buildParam func(int) string
8080
if len(options) > 0 && options[0] != nil {
@@ -86,7 +86,7 @@ func NewSqlDiffReader(db *sql.DB, table string, entity string, entityType string
8686
}
8787

8888
func NewSqlDiffListReader(db *sql.DB, table string, entity string, entityType string, idNames []string, config DiffConfig, keyBuilder KeyBuilder, options...func(int) string) *SqlDiffListReader {
89-
columnSelect := BuildQueryColumn(config)
89+
columnSelect := buildQueryColumns(config)
9090
driver := getDriver(db)
9191
var buildParam func(int) string
9292
if len(options) > 0 && options[0] != nil {
@@ -235,7 +235,7 @@ func (r SqlDiffReader) getEntityById(ctx context.Context, key interface{}, idNam
235235
querySql := fmt.Sprintf("select %s from %s where %s = %s and %s = %s", r.columnSelect, r.Entity,
236236
r.Config.Id, r.BuildParam(1),
237237
r.EntityType, r.BuildParam(2))
238-
err := SqlQueryOne(ctx, r.DB, &result, querySql, key, r.Table)
238+
err := QueryDiff(ctx, r.DB, &result, querySql, key, r.Table)
239239
if err != nil {
240240
return nil, err
241241
}
@@ -245,16 +245,16 @@ func (r SqlDiffReader) getEntityById(ctx context.Context, key interface{}, idNam
245245
return &result, nil
246246
}
247247

248-
func BuildParameters(numCol int, buildParam func(int) string) string {
248+
func buildParameters(numCol int, buildParam func(int) string) string {
249249
var arrValue []string
250250
for i := 0; i < numCol; i++ {
251251
arrValue = append(arrValue, buildParam(i+1))
252252
}
253253
return strings.Join(arrValue, ",")
254254
}
255-
func BuildQueryColumn(config DiffConfig) string {
255+
func buildQueryColumns(config DiffConfig) string {
256256
sqlsel := make([]string, 0)
257-
colDiffModel := GetColumnNameDiffModel()
257+
colDiffModel := getDiffColumnNames()
258258
if config.Id != "" {
259259
sqlsel = append(sqlsel, config.Id+" as "+colDiffModel[0])
260260
}
@@ -270,7 +270,7 @@ func BuildQueryColumn(config DiffConfig) string {
270270
return strings.Join(sqlsel, ",")
271271
}
272272

273-
func GetColumnNameDiffModel() []string {
273+
func getDiffColumnNames() []string {
274274
ids := make([]string, 0)
275275
objectValue := reflect.Indirect(reflect.ValueOf(DiffModel{}))
276276
for i := 0; i < objectValue.NumField(); i++ {
@@ -314,8 +314,8 @@ func (c SqlDiffListReader) getEntityByIds(ctx context.Context, keyBuilder KeyBui
314314
args = append(args, arrayKeys...)
315315
args = append(args, c.Table)
316316
results := make([]DiffModel, 0)
317-
querySql := fmt.Sprintf("select %s from %s where %s IN (%s) and %s = %s", c.columnSelect, c.Entity, c.Config.Id, BuildParameters(n, c.BuildParam), c.EntityType, c.BuildParam(n+1))
318-
err := Query(ctx, c.DB, &results, querySql, args...)
317+
querySql := fmt.Sprintf("select %s from %s where %s IN (%s) and %s = %s", c.columnSelect, c.Entity, c.Config.Id, buildParameters(n, c.BuildParam), c.EntityType, c.BuildParam(n+1))
318+
err := QueryDiffs(ctx, c.DB, &results, querySql, args...)
319319
// map object id
320320
for i, result := range results {
321321
id := result.Id.(*string)
@@ -358,7 +358,7 @@ func (b *DefaultKeyBuilder) getPositionPrimaryKeys(modelType reflect.Type) []int
358358
return b.PositionPrimaryKeysMap[modelType]
359359
}
360360

361-
func SqlQueryOne(ctx context.Context, db *sql.DB, result *DiffModel, sql string, values ...interface{}) error {
361+
func QueryDiff(ctx context.Context, db *sql.DB, result *DiffModel, sql string, values ...interface{}) error {
362362
driver := getDriver(db)
363363
suffix := " limit 1 "
364364
if driver == DriverOracle {
@@ -431,7 +431,7 @@ func convertStringToMap(str *string) (*map[string]interface{}, error) {
431431
return &p, err
432432
}
433433

434-
func Query(ctx context.Context, db *sql.DB, results *[]DiffModel, sql string, values ...interface{}) error {
434+
func QueryDiffs(ctx context.Context, db *sql.DB, results *[]DiffModel, sql string, values ...interface{}) error {
435435
rows, err := db.QueryContext(ctx, sql, values...)
436436
if err != nil {
437437
return err

0 commit comments

Comments
 (0)