-
Notifications
You must be signed in to change notification settings - Fork 5
/
schema.go
299 lines (271 loc) · 6.35 KB
/
schema.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
package orm
import (
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
)
func getConnectionFor(e Entity) *connection {
configurator := newEntityConfigurator()
e.ConfigureEntity(configurator)
if len(globalConnections) > 1 && (configurator.connection == "" || configurator.table == "") {
panic("need table and DB name when having more than 1 DB registered")
}
if len(globalConnections) == 1 {
for _, db := range globalConnections {
return db
}
}
if db, exists := globalConnections[fmt.Sprintf("%s", configurator.connection)]; exists {
return db
}
panic("no db found")
}
func getSchemaFor(e Entity) *schema {
configurator := newEntityConfigurator()
c := getConnectionFor(e)
e.ConfigureEntity(configurator)
s := c.getSchema(configurator.table)
if s == nil {
s = schemaOfHeavyReflectionStuff(e)
c.setSchema(e, s)
}
return s
}
type schema struct {
Connection string
Table string
fields []*field
relations map[string]interface{}
setPK func(o Entity, value interface{})
getPK func(o Entity) interface{}
columnConstraints []*FieldConfigurator
}
func (s *schema) getField(sf reflect.StructField) *field {
for _, f := range s.fields {
if sf.Name == f.Name {
return f
}
}
return nil
}
func (s *schema) getDialect() *Dialect {
return GetConnection(s.Connection).Dialect
}
func (s *schema) Columns(withPK bool) []string {
var cols []string
for _, field := range s.fields {
if field.Virtual {
continue
}
if !withPK && field.IsPK {
continue
}
if s.getDialect().AddTableNameInSelectColumns {
cols = append(cols, s.Table+"."+field.Name)
} else {
cols = append(cols, field.Name)
}
}
return cols
}
func (s *schema) pkName() string {
for _, field := range s.fields {
if field.IsPK {
return field.Name
}
}
return ""
}
func genericFieldsOf(obj Entity) []*field {
t := reflect.TypeOf(obj)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Slice {
t = t.Elem()
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
}
var ec EntityConfigurator
obj.ConfigureEntity(&ec)
var fms []*field
for i := 0; i < t.NumField(); i++ {
ft := t.Field(i)
fm := fieldMetadata(ft, ec.columnConstraints)
fms = append(fms, fm...)
}
return fms
}
func valuesOfField(vf reflect.Value) []interface{} {
var values []interface{}
if vf.Type().Kind() == reflect.Struct || vf.Type().Kind() == reflect.Ptr {
t := vf.Type()
if vf.Type().Kind() == reflect.Ptr {
t = vf.Type().Elem()
}
if !t.Implements(reflect.TypeOf((*driver.Valuer)(nil)).Elem()) {
// go into
// it does not implement driver.Valuer interface
for i := 0; i < vf.NumField(); i++ {
vif := vf.Field(i)
values = append(values, valuesOfField(vif)...)
}
} else {
values = append(values, vf.Interface())
}
} else {
values = append(values, vf.Interface())
}
return values
}
func genericValuesOf(o Entity, withPK bool) []interface{} {
t := reflect.TypeOf(o)
v := reflect.ValueOf(o)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
fields := getSchemaFor(o).fields
pkIdx := -1
for i, field := range fields {
if field.IsPK {
pkIdx = i
}
}
var values []interface{}
for i := 0; i < t.NumField(); i++ {
if !withPK && i == pkIdx {
continue
}
if fields[i].Virtual {
continue
}
vf := v.Field(i)
values = append(values, valuesOfField(vf)...)
}
return values
}
func genericSetPkValue(obj Entity, value interface{}) {
genericSet(obj, getSchemaFor(obj).pkName(), value)
}
func genericGetPKValue(obj Entity) interface{} {
t := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
if t.Kind() == reflect.Ptr {
val = val.Elem()
}
fields := getSchemaFor(obj).fields
for i, field := range fields {
if field.IsPK {
return val.Field(i).Interface()
}
}
return ""
}
func (s *schema) createdAt() *field {
for _, f := range s.fields {
if f.IsCreatedAt {
return f
}
}
return nil
}
func (s *schema) updatedAt() *field {
for _, f := range s.fields {
if f.IsUpdatedAt {
return f
}
}
return nil
}
func (s *schema) deletedAt() *field {
for _, f := range s.fields {
if f.IsDeletedAt {
return f
}
}
return nil
}
func pointersOf(v reflect.Value) map[string]interface{} {
m := map[string]interface{}{}
actualV := v
for actualV.Type().Kind() == reflect.Ptr {
actualV = actualV.Elem()
}
for i := 0; i < actualV.NumField(); i++ {
f := actualV.Field(i)
if (f.Type().Kind() == reflect.Struct || f.Type().Kind() == reflect.Ptr) && !f.Type().Implements(reflect.TypeOf((*driver.Valuer)(nil)).Elem()) {
fm := pointersOf(f)
for k, p := range fm {
m[k] = p
}
} else {
fm := fieldMetadata(actualV.Type().Field(i), nil)[0]
m[fm.Name] = actualV.Field(i)
}
}
return m
}
func genericSet(obj Entity, name string, value interface{}) {
n2p := pointersOf(reflect.ValueOf(obj))
var val interface{}
for k, v := range n2p {
if k == name {
val = v
}
}
val.(reflect.Value).Set(reflect.ValueOf(value))
}
func schemaOfHeavyReflectionStuff(v Entity) *schema {
userEntityConfigurator := newEntityConfigurator()
v.ConfigureEntity(userEntityConfigurator)
for _, relation := range userEntityConfigurator.resolveRelations {
relation()
}
schema := &schema{}
if userEntityConfigurator.connection != "" {
schema.Connection = userEntityConfigurator.connection
}
if userEntityConfigurator.table != "" {
schema.Table = userEntityConfigurator.table
} else {
panic("you need to have table name for getting schema.")
}
schema.columnConstraints = userEntityConfigurator.columnConstraints
if schema.Connection == "" {
schema.Connection = "default"
}
if schema.fields == nil {
schema.fields = genericFieldsOf(v)
}
if schema.getPK == nil {
schema.getPK = genericGetPKValue
}
if schema.setPK == nil {
schema.setPK = genericSetPkValue
}
schema.relations = userEntityConfigurator.relations
return schema
}
func (s *schema) getTable() string {
return s.Table
}
func (s *schema) getSQLDB() *sql.DB {
return s.getConnection().DB
}
func (s *schema) getConnection() *connection {
if len(globalConnections) > 1 && (s.Connection == "" || s.Table == "") {
panic("need table and DB name when having more than 1 DB registered")
}
if len(globalConnections) == 1 {
for _, db := range globalConnections {
return db
}
}
if db, exists := globalConnections[fmt.Sprintf("%s", s.Connection)]; exists {
return db
}
panic("no db found")
}