-
Notifications
You must be signed in to change notification settings - Fork 101
/
model.go
424 lines (396 loc) · 9.06 KB
/
model.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package qbs
import (
"bytes"
"database/sql"
"reflect"
"strconv"
"strings"
"time"
)
type TableNamer interface {
TableName() string
}
const QBS_COLTYPE_INT = "int"
const QBS_COLTYPE_BOOL = "boolean"
const QBS_COLTYPE_BIGINT = "bigint"
const QBS_COLTYPE_DOUBLE = "double"
const QBS_COLTYPE_TIME = "timestamp"
const QBS_COLTYPE_TEXT = "text"
//convert struct field name to column name.
var FieldNameToColumnName func(string) string = toSnake
//convert struct name to table name.
var StructNameToTableName func(string) string = toSnake
//onvert column name to struct field name.
var ColumnNameToFieldName func(string) string = snakeToUpperCamel
//convert table name to struct name.
var TableNameToStructName func(string) string = snakeToUpperCamel
// Index represents a table index and is returned via the Indexed interface.
type index struct {
name string
columns []string
unique bool
}
// Indexes represents an array of indexes.
type Indexes []*index
type Indexed interface {
Indexes(indexes *Indexes)
}
// Add adds an index
func (ix *Indexes) Add(columns ...string) {
name := strings.Join(columns, "_")
*ix = append(*ix, &index{name: name, columns: columns, unique: false})
}
// AddUnique adds an unique index
func (ix *Indexes) AddUnique(columns ...string) {
name := strings.Join(columns, "_")
*ix = append(*ix, &index{name: name, columns: columns, unique: true})
}
// ModelField represents a schema field of a parsed model.
type modelField struct {
name string // Column name
camelName string
value interface{} // Value
pk bool
notnull bool
index bool
unique bool
updated bool
created bool
size int
dfault string
fk string
join string
colType string
nullable reflect.Kind
}
// Model represents a parsed schema interface{}.
type model struct {
pk *modelField
table string
fields []*modelField
refs map[string]*reference
indexes Indexes
}
type reference struct {
refKey string
model *model
foreignKey bool
}
func (model *model) columnsAndValues(forUpdate bool) ([]string, []interface{}) {
columns := make([]string, 0, len(model.fields))
values := make([]interface{}, 0, len(columns))
for _, column := range model.fields {
var include bool
if forUpdate {
include = column.value != nil && !column.pk
} else {
include = true
if column.value == nil && column.nullable == reflect.Invalid {
include = false
} else if column.pk {
if intValue, ok := column.value.(int64); ok {
include = intValue != 0
} else if strValue, ok := column.value.(string); ok {
include = strValue != ""
}
}
}
if include {
columns = append(columns, column.name)
values = append(values, column.value)
}
}
return columns, values
}
func (model *model) timeField(name string) *modelField {
for _, v := range model.fields {
if _, ok := v.value.(time.Time); ok {
if name == "created" {
if v.created {
return v
}
} else if name == "updated" {
if v.updated {
return v
}
}
if v.name == name {
return v
}
}
}
return nil
}
func (model *model) pkZero() bool {
if model.pk == nil {
return true
}
switch model.pk.value.(type) {
case string:
return model.pk.value.(string) == ""
case int8:
return model.pk.value.(int8) == 0
case int16:
return model.pk.value.(int16) == 0
case int32:
return model.pk.value.(int32) == 0
case int64:
return model.pk.value.(int64) == 0
case uint8:
return model.pk.value.(uint8) == 0
case uint16:
return model.pk.value.(uint16) == 0
case uint32:
return model.pk.value.(uint32) == 0
case uint64:
return model.pk.value.(uint64) == 0
}
return true
}
func structPtrToModel(f interface{}, root bool, omitFields []string) *model {
model := &model{
pk: nil,
table: tableName(f),
fields: []*modelField{},
indexes: Indexes{},
}
structType := reflect.TypeOf(f).Elem()
structValue := reflect.ValueOf(f).Elem()
if structType.Kind() == reflect.Ptr {
if structType.Elem().Kind() == reflect.Struct {
panic("did you pass a pointer to a pointer to a struct?")
}
}
for i := 0; i < structType.NumField(); i++ {
structField := structType.Field(i)
omit := false
for _, v := range omitFields {
if v == structField.Name {
omit = true
}
}
if omit {
continue
}
fieldValue := structValue.FieldByName(structField.Name)
if !fieldValue.CanInterface() {
continue
}
sqlTag := structField.Tag.Get("qbs")
if sqlTag == "-" {
continue
}
fieldIsNullable := false
kind := structField.Type.Kind()
switch kind {
case reflect.Ptr:
switch structField.Type.Elem().Kind() {
case reflect.Bool, reflect.String, reflect.Int64, reflect.Float64:
kind = structField.Type.Elem().Kind()
fieldIsNullable = true
default:
continue
}
case reflect.Map:
continue
case reflect.Slice:
elemKind := structField.Type.Elem().Kind()
if elemKind != reflect.Uint8 {
continue
}
}
fd := new(modelField)
parseTags(fd, sqlTag)
fd.camelName = structField.Name
fd.name = FieldNameToColumnName(structField.Name)
if fieldIsNullable {
fd.nullable = kind
if fieldValue.IsNil() {
fd.value = nil
} else {
fd.value = fieldValue.Elem().Interface()
}
} else {
//not nullable case
fd.value = fieldValue.Interface()
}
if _, ok := fd.value.(int64); ok && fd.camelName == "Id" {
fd.pk = true
}
if fd.pk {
model.pk = fd
}
model.fields = append(model.fields, fd)
// fill in references map only in root model.
if root {
var fk, explicitJoin, implicitJoin bool
var refName string
if fd.fk != "" {
refName = fd.fk
fk = true
} else if fd.join != "" {
refName = fd.join
explicitJoin = true
}
if len(fd.camelName) > 3 && strings.HasSuffix(fd.camelName, "Id") {
fdValue := reflect.ValueOf(fd.value)
if _, ok := fd.value.(sql.NullInt64); ok || fdValue.Kind() == reflect.Int64 {
i := strings.LastIndex(fd.camelName, "Id")
refName = fd.camelName[:i]
implicitJoin = true
}
}
if fk || explicitJoin || implicitJoin {
omit := false
for _, v := range omitFields {
if v == refName {
omit = true
}
}
if field, ok := structType.FieldByName(refName); ok && !omit {
fieldValue := structValue.FieldByName(refName)
if fieldValue.Kind() == reflect.Ptr {
model.indexes.Add(fd.name)
if fieldValue.IsNil() {
fieldValue.Set(reflect.New(field.Type.Elem()))
}
refModel := structPtrToModel(fieldValue.Interface(), false, nil)
ref := new(reference)
ref.foreignKey = fk
ref.model = refModel
ref.refKey = fd.name
if model.refs == nil {
model.refs = make(map[string]*reference)
}
model.refs[refName] = ref
} else if !implicitJoin {
panic("Referenced field is not pointer")
}
} else if !implicitJoin {
panic("Can not find referenced field")
}
}
if fd.unique {
model.indexes.AddUnique(fd.name)
} else if fd.index {
model.indexes.Add(fd.name)
}
}
}
if root {
if indexed, ok := f.(Indexed); ok {
indexed.Indexes(&model.indexes)
}
}
return model
}
func tableName(talbe interface{}) string {
if t, ok := talbe.(string); ok {
return t
}
t := reflect.TypeOf(talbe).Elem()
for {
c := false
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
t = t.Elem()
c = true
}
if !c {
break
}
}
if tn, ok := talbe.(TableNamer); ok {
return tn.TableName()
}
return StructNameToTableName(t.Name())
}
func parseTags(fd *modelField, s string) {
if s == "" {
return
}
c := strings.Split(s, ",")
for _, v := range c {
c2 := strings.Split(v, ":")
if len(c2) == 2 {
switch c2[0] {
case "fk":
fd.fk = c2[1]
case "size":
fd.size, _ = strconv.Atoi(c2[1])
case "default":
fd.dfault = c2[1]
case "join":
fd.join = c2[1]
case "coltype":
fd.colType = c2[1]
default:
panic(c2[0] + " tag syntax error")
}
} else {
switch c2[0] {
case "created":
fd.created = true
case "pk":
fd.pk = true
case "updated":
fd.updated = true
case "index":
fd.index = true
case "unique":
fd.unique = true
case "notnull":
fd.notnull = true
default:
panic(c2[0] + " tag syntax error")
}
}
}
return
}
func toSnake(s string) string {
buf := new(bytes.Buffer)
for i := 0; i < len(s); i++ {
c := s[i]
if c >= 'A' && c <= 'Z' {
if i > 0 {
buf.WriteByte('_')
}
buf.WriteByte(c + 32)
} else {
buf.WriteByte(c)
}
}
return buf.String()
}
func snakeToUpperCamel(s string) string {
buf := new(bytes.Buffer)
first := true
for i := 0; i < len(s); i++ {
c := s[i]
if c >= 'a' && c <= 'z' && first {
buf.WriteByte(c - 32)
first = false
} else if c == '_' {
first = true
continue
} else {
buf.WriteByte(c)
}
}
return buf.String()
}
var ValidTags = map[string]bool{
"pk": true, //primary key
"fk": true, //foreign key
"size": true,
"default": true,
"join": true,
"-": true, //ignore
"index": true,
"unique": true,
"notnull": true,
"updated": true,
"created": true,
"coltype": true,
}