-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.go
252 lines (235 loc) · 6.5 KB
/
loader.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
package cassandra
import (
"context"
"fmt"
"github.com/apache/cassandra-gocql-driver"
"reflect"
"strings"
)
func InitFields(modelType reflect.Type) (map[string]int, string, error) {
fieldsIndex, err := GetColumnIndexes(modelType)
if err != nil {
return nil, "", err
}
fields := BuildFields(modelType)
return fieldsIndex, fields, nil
}
type Loader struct {
DB *gocql.ClusterConfig
BuildParam func(i int) string
Map func(ctx context.Context, model interface{}) (interface{}, error)
modelType reflect.Type
modelsType reflect.Type
keys []string
mapJsonColumnKeys map[string]string
fieldsIndex map[string]int
table string
query string
}
func NewLoader(db *gocql.ClusterConfig, tableName string, modelType reflect.Type, options ...func(context.Context, interface{}) (interface{}, error)) (*Loader, error) {
_, idNames := FindPrimaryKeys(modelType)
mapJsonColumnKeys := MapJsonColumn(modelType)
modelsType := reflect.Zero(reflect.SliceOf(modelType)).Type()
fieldsIndex, er0 := GetColumnIndexes(modelType)
if er0 != nil {
return nil, er0
}
var mp func(context.Context, interface{}) (interface{}, error)
if len(options) > 0 {
mp = options[0]
}
query := BuildQuery(tableName, modelType)
return &Loader{DB: db, BuildParam: BuildParam, Map: mp, modelType: modelType, modelsType: modelsType, keys: idNames, mapJsonColumnKeys: mapJsonColumnKeys, fieldsIndex: fieldsIndex, table: tableName, query: query}, nil
}
func (s *Loader) Keys() []string {
return s.keys
}
func (s *Loader) All(ctx context.Context) (interface{}, error) {
result := reflect.New(s.modelsType).Interface()
ses, err := s.DB.CreateSession()
if err != nil {
return nil, err
}
defer ses.Close()
q := ses.Query(s.query)
err = q.Exec()
if err != nil {
return nil, err
}
err = ScanIter(q.Iter(), result, s.fieldsIndex)
if err == nil {
if s.Map != nil {
return MapModels(ctx, result, s.Map)
}
}
return result, err
}
func (s *Loader) Load(ctx context.Context, id interface{}) (interface{}, error) {
queryFindById, values := BuildFindById(s.query, id, s.mapJsonColumnKeys, s.keys)
ses, err := s.DB.CreateSession()
if err != nil {
return nil, err
}
defer ses.Close()
q := ses.Query(queryFindById, values...)
err = q.Exec()
if err != nil {
return nil, err
}
arr, err := Scan(q.Iter(), s.modelType, s.fieldsIndex)
if err != nil {
return nil, err
}
if len(arr) > 0 {
if s.Map != nil {
_, er2 := s.Map(ctx, &arr[0])
return &arr[0], er2
}
return &arr[0], nil
} else {
return nil, nil
}
}
func (s *Loader) LoadAndDecode(ctx context.Context, id interface{}, result interface{}) (bool, error) {
return s.Get(ctx, id, result)
}
func (s *Loader) Get(ctx context.Context, id interface{}, result interface{}) (bool, error) {
queryFindById, values := BuildFindById(s.query, id, s.mapJsonColumnKeys, s.keys)
ses, err := s.DB.CreateSession()
if err != nil {
return false, err
}
defer ses.Close()
q := ses.Query(queryFindById, values...)
err = q.Exec()
if err != nil {
return false, err
}
iter := q.Iter()
columns := GetColumns(iter.Columns())
r := StructScan(result, columns, s.fieldsIndex, -1)
if !iter.Scan(r...) {
return false, nil
} else {
if s.Map != nil {
_, er2 := s.Map(ctx, result)
return true, er2
}
return true, nil
}
}
func (s *Loader) Exist(ctx context.Context, id interface{}) (bool, error) {
v, err := s.Load(ctx, id)
if err != nil {
return false, err
}
ok := IsNil(v)
return ok, nil
}
func FindPrimaryKeys(modelType reflect.Type) ([]string, []string) {
numField := modelType.NumField()
var idColumnFields []string
var idJsons []string
for i := 0; i < numField; i++ {
field := modelType.Field(i)
ormTag := field.Tag.Get("gorm")
tags := strings.Split(ormTag, ";")
for _, tag := range tags {
if strings.Compare(strings.TrimSpace(tag), "primary_key") == 0 {
k, ok := findTag(ormTag, "column")
if ok {
idColumnFields = append(idColumnFields, k)
tag1, ok1 := field.Tag.Lookup("json")
tagJsons := strings.Split(tag1, ",")
if ok1 && len(tagJsons) > 0 {
idJsons = append(idJsons, tagJsons[0])
}
}
}
}
}
return idColumnFields, idJsons
}
func findTag(tag string, key string) (string, bool) {
if has := strings.Contains(tag, key); has {
str1 := strings.Split(tag, ";")
num := len(str1)
for i := 0; i < num; i++ {
str2 := strings.Split(str1[i], ":")
for j := 0; j < len(str2); j++ {
if str2[j] == key {
return str2[j+1], true
}
}
}
}
return "", false
}
func MapJsonColumn(modelType reflect.Type) map[string]string {
numField := modelType.NumField()
columnNameKeys := make(map[string]string)
for i := 0; i < numField; i++ {
field := modelType.Field(i)
ormTag := field.Tag.Get("gorm")
tags := strings.Split(ormTag, ";")
for _, tag := range tags {
if strings.Compare(strings.TrimSpace(tag), "primary_key") == 0 {
if has := strings.Contains(ormTag, "column"); has {
str1 := strings.Split(ormTag, ";")
num := len(str1)
for i := 0; i < num; i++ {
str2 := strings.Split(str1[i], ":")
for j := 0; j < len(str2); j++ {
if str2[j] == "column" {
tagj, ok1 := field.Tag.Lookup("json")
t := strings.Split(tagj, ",")
if ok1 && len(t) > 0 {
json := t[0]
columnNameKeys[json] = str2[j+1]
}
}
}
}
}
}
}
}
return columnNameKeys
}
func BuildSelectAllQuery(table string) string {
return fmt.Sprintf("select * from %v", table)
}
func BuildFindById(query string, id interface{}, mapJsonColumnKeys map[string]string, keys []string) (string, []interface{}) {
buildParam := BuildParam
var where = ""
var values []interface{}
if len(keys) == 1 {
where = fmt.Sprintf("where %s = %s", mapJsonColumnKeys[keys[0]], buildParam(1))
values = append(values, id)
} else {
conditions := make([]string, 0)
if ids, ok := id.(map[string]interface{}); ok {
j := 0
for _, keyJson := range keys {
columnName := mapJsonColumnKeys[keyJson]
if idk, ok1 := ids[keyJson]; ok1 {
conditions = append(conditions, fmt.Sprintf("%s = %s", columnName, buildParam(j)))
values = append(values, idk)
j++
}
}
where = "where " + strings.Join(conditions, " and ")
}
}
return fmt.Sprintf("%v %v", query, where), values
}
func IsNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}