Debian Codegraph @

schema/schema.go

raw
1 package schema
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "go/ast"
8 "path"
9 "reflect"
10 "strings"
11 "sync"
12
13 "gorm.io/gorm/clause"
14 "gorm.io/gorm/logger"
15 )
16
17 type callbackType string
18
19 const (
20 callbackTypeBeforeCreate callbackType = "BeforeCreate"
21 callbackTypeBeforeUpdate callbackType = "BeforeUpdate"
22 callbackTypeAfterCreate callbackType = "AfterCreate"
23 callbackTypeAfterUpdate callbackType = "AfterUpdate"
24 callbackTypeBeforeSave callbackType = "BeforeSave"
25 callbackTypeAfterSave callbackType = "AfterSave"
26 callbackTypeBeforeDelete callbackType = "BeforeDelete"
27 callbackTypeAfterDelete callbackType = "AfterDelete"
28 callbackTypeAfterFind callbackType = "AfterFind"
29 )
30
31 // ErrUnsupportedDataType unsupported data type
32 var ErrUnsupportedDataType = errors.New("unsupported data type")
33
34 type Schema struct {
35 Name string
36 ModelType reflect.Type
37 Table string
38 PrioritizedPrimaryField *Field
39 DBNames []string
40 PrimaryFields []*Field
41 PrimaryFieldDBNames []string
42 Fields []*Field
43 FieldsByName map[string]*Field
44 FieldsByBindName map[string]*Field // embedded fields is 'Embed.Field'
45 FieldsByDBName map[string]*Field
46 FieldsWithDefaultDBValue []*Field // fields with default value assigned by database
47 Relationships Relationships
48 CreateClauses []clause.Interface
49 QueryClauses []clause.Interface
50 UpdateClauses []clause.Interface
51 DeleteClauses []clause.Interface
52 BeforeCreate, AfterCreate bool
53 BeforeUpdate, AfterUpdate bool
54 BeforeDelete, AfterDelete bool
55 BeforeSave, AfterSave bool
56 AfterFind bool
57 err error
58 initialized chan struct{}
59 namer Namer
60 cacheStore *sync.Map
61 }
62
63 func (schema *Schema) String() string {
64 if schema.ModelType.Name() == "" {
65 return fmt.Sprintf("%s(%s)", schema.Name, schema.Table)
66 }
67 return fmt.Sprintf("%s.%s", schema.ModelType.PkgPath(), schema.ModelType.Name())
68 }
69
70 func (schema *Schema) MakeSlice() reflect.Value {
71 slice := reflect.MakeSlice(reflect.SliceOf(reflect.PointerTo(schema.ModelType)), 0, 20)
72 results := reflect.New(slice.Type())
73 results.Elem().Set(slice)
74
75 return results
76 }
77
78 func (schema *Schema) LookUpField(name string) *Field {
79 if field, ok := schema.FieldsByDBName[name]; ok {
80 return field
81 }
82 if field, ok := schema.FieldsByName[name]; ok {
83 return field
84 }
85
86 // Lookup field using namer-driven ColumnName
87 if schema.namer == nil {
88 return nil
89 }
90 namerColumnName := schema.namer.ColumnName(schema.Table, name)
91 if field, ok := schema.FieldsByDBName[namerColumnName]; ok {
92 return field
93 }
94
95 return nil
96 }
97
98 // LookUpFieldByBindName looks for the closest field in the embedded struct.
99 //
100 // type Struct struct {
101 // Embedded struct {
102 // ID string // is selected by LookUpFieldByBindName([]string{"Embedded", "ID"}, "ID")
103 // }
104 // ID string // is selected by LookUpFieldByBindName([]string{"ID"}, "ID")
105 // }
106 func (schema *Schema) LookUpFieldByBindName(bindNames []string, name string) *Field {
107 for i := len(bindNames) - 1; i >= 0; i-- {
108 find := strings.Join(bindNames[:i], ".") + "." + name
109 if field, ok := schema.FieldsByBindName[find]; ok {
110 return field
111 }
112 }
113 return nil
114 }
115
116 type Tabler interface {
117 TableName() string
118 }
119
120 type TablerWithNamer interface {
121 TableName(Namer) string
122 }
123
124 var callbackTypes = []callbackType{
125 callbackTypeBeforeCreate, callbackTypeAfterCreate,
126 callbackTypeBeforeUpdate, callbackTypeAfterUpdate,
127 callbackTypeBeforeSave, callbackTypeAfterSave,
128 callbackTypeBeforeDelete, callbackTypeAfterDelete,
129 callbackTypeAfterFind,
130 }
131
132 // Parse get data type from dialector
133 func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) {
134 return ParseWithSpecialTableName(dest, cacheStore, namer, "")
135 }
136
137 // ParseWithSpecialTableName get data type from dialector with extra schema table
138 func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Namer, specialTableName string) (*Schema, error) {
139 if dest == nil {
140 return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest)
141 }
142
143 modelType := reflect.ValueOf(dest).Type()
144 if modelType.Kind() == reflect.Ptr {
145 modelType = modelType.Elem()
146 }
147
148 if modelType.Kind() != reflect.Struct {
149 if modelType.Kind() == reflect.Interface {
150 modelType = reflect.Indirect(reflect.ValueOf(dest)).Elem().Type()
151 }
152
153 for modelType.Kind() == reflect.Slice || modelType.Kind() == reflect.Array || modelType.Kind() == reflect.Ptr {
154 modelType = modelType.Elem()
155 }
156
157 if modelType.Kind() != reflect.Struct {
158 if modelType.PkgPath() == "" {
159 return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest)
160 }
161 return nil, fmt.Errorf("%w: %s.%s", ErrUnsupportedDataType, modelType.PkgPath(), modelType.Name())
162 }
163 }
164
165 // Cache the Schema for performance,
166 // Use the modelType or modelType + schemaTable (if it present) as cache key.
167 var schemaCacheKey interface{} = modelType
168 if specialTableName != "" {
169 schemaCacheKey = fmt.Sprintf("%p-%s", modelType, specialTableName)
170 }
171
172 // Load exist schema cache, return if exists
173 if v, ok := cacheStore.Load(schemaCacheKey); ok {
174 s := v.(*Schema)
175 // Wait for the initialization of other goroutines to complete
176 <-s.initialized
177 return s, s.err
178 }
179
180 var tableName string
181 modelValue := reflect.New(modelType)
182 if specialTableName != "" {
183 tableName = specialTableName
184 } else if en, ok := namer.(embeddedNamer); ok {
185 tableName = en.Table
186 } else if tabler, ok := modelValue.Interface().(Tabler); ok {
187 tableName = tabler.TableName()
188 } else if tabler, ok := modelValue.Interface().(TablerWithNamer); ok {
189 tableName = tabler.TableName(namer)
190 } else {
191 tableName = namer.TableName(modelType.Name())
192 }
193
194 schema := &Schema{
195 Name: modelType.Name(),
196 ModelType: modelType,
197 Table: tableName,
198 DBNames: make([]string, 0, 10),
199 Fields: make([]*Field, 0, 10),
200 FieldsByName: make(map[string]*Field, 10),
201 FieldsByBindName: make(map[string]*Field, 10),
202 FieldsByDBName: make(map[string]*Field, 10),
203 Relationships: Relationships{Relations: map[string]*Relationship{}},
204 cacheStore: cacheStore,
205 namer: namer,
206 initialized: make(chan struct{}),
207 }
208 // When the schema initialization is completed, the channel will be closed
209 defer close(schema.initialized)
210
211 // Load exist schema cache, return if exists
212 if v, ok := cacheStore.Load(schemaCacheKey); ok {
213 s := v.(*Schema)
214 // Wait for the initialization of other goroutines to complete
215 <-s.initialized
216 return s, s.err
217 }
218
219 for i := 0; i < modelType.NumField(); i++ {
220 if fieldStruct := modelType.Field(i); ast.IsExported(fieldStruct.Name) {
221 if field := schema.ParseField(fieldStruct); field.EmbeddedSchema != nil {
222 schema.Fields = append(schema.Fields, field.EmbeddedSchema.Fields...)
223 } else {
224 schema.Fields = append(schema.Fields, field)
225 }
226 }
227 }
228
229 for _, field := range schema.Fields {
230 if field.DBName == "" && field.DataType != "" {
231 field.DBName = namer.ColumnName(schema.Table, field.Name)
232 }
233
234 bindName := field.BindName()
235 if field.DBName != "" {
236 // nonexistence or shortest path or first appear prioritized if has permission
237 if v, ok := schema.FieldsByDBName[field.DBName]; !ok || ((field.Creatable || field.Updatable || field.Readable) && len(field.BindNames) < len(v.BindNames)) {
238 if _, ok := schema.FieldsByDBName[field.DBName]; !ok {
239 schema.DBNames = append(schema.DBNames, field.DBName)
240 }
241 schema.FieldsByDBName[field.DBName] = field
242 schema.FieldsByName[field.Name] = field
243 schema.FieldsByBindName[bindName] = field
244
245 if v != nil && v.PrimaryKey {
246 // remove the existing primary key field
247 for idx, f := range schema.PrimaryFields {
248 if f.DBName == v.DBName {
249 schema.PrimaryFields = append(schema.PrimaryFields[0:idx], schema.PrimaryFields[idx+1:]...)
250 }
251 }
252 }
253
254 if field.PrimaryKey {
255 schema.PrimaryFields = append(schema.PrimaryFields, field)
256 }
257 }
258 }
259
260 if of, ok := schema.FieldsByName[field.Name]; !ok || of.TagSettings["-"] == "-" {
261 schema.FieldsByName[field.Name] = field
262 }
263 if of, ok := schema.FieldsByBindName[bindName]; !ok || of.TagSettings["-"] == "-" {
264 schema.FieldsByBindName[bindName] = field
265 }
266
267 field.setupValuerAndSetter(modelType)
268 }
269
270 prioritizedPrimaryField := schema.LookUpField("id")
271 if prioritizedPrimaryField == nil {
272 prioritizedPrimaryField = schema.LookUpField("ID")
273 }
274
275 if prioritizedPrimaryField != nil {
276 if prioritizedPrimaryField.PrimaryKey {
277 schema.PrioritizedPrimaryField = prioritizedPrimaryField
278 } else if len(schema.PrimaryFields) == 0 {
279 prioritizedPrimaryField.PrimaryKey = true
280 schema.PrioritizedPrimaryField = prioritizedPrimaryField
281 schema.PrimaryFields = append(schema.PrimaryFields, prioritizedPrimaryField)
282 }
283 }
284
285 if schema.PrioritizedPrimaryField == nil {
286 if len(schema.PrimaryFields) == 1 {
287 schema.PrioritizedPrimaryField = schema.PrimaryFields[0]
288 } else if len(schema.PrimaryFields) > 1 {
289 // If there are multiple primary keys, the AUTOINCREMENT field is prioritized
290 for _, field := range schema.PrimaryFields {
291 if field.AutoIncrement {
292 schema.PrioritizedPrimaryField = field
293 break
294 }
295 }
296 }
297 }
298
299 for _, field := range schema.PrimaryFields {
300 schema.PrimaryFieldDBNames = append(schema.PrimaryFieldDBNames, field.DBName)
301 }
302
303 _, embedded := schema.cacheStore.Load(embeddedCacheKey)
304 relationshipFields := []*Field{}
305 for _, field := range schema.Fields {
306 if field.DataType != "" && field.HasDefaultValue && field.DefaultValueInterface == nil {
307 schema.FieldsWithDefaultDBValue = append(schema.FieldsWithDefaultDBValue, field)
308 }
309
310 if !embedded {
311 if field.DataType == "" && field.GORMDataType == "" && (field.Creatable || field.Updatable || field.Readable) {
312 relationshipFields = append(relationshipFields, field)
313 schema.FieldsByName[field.Name] = field
314 schema.FieldsByBindName[field.BindName()] = field
315 }
316
317 fieldValue := reflect.New(field.IndirectFieldType).Interface()
318 if fc, ok := fieldValue.(CreateClausesInterface); ok {
319 field.Schema.CreateClauses = append(field.Schema.CreateClauses, fc.CreateClauses(field)...)
320 }
321
322 if fc, ok := fieldValue.(QueryClausesInterface); ok {
323 field.Schema.QueryClauses = append(field.Schema.QueryClauses, fc.QueryClauses(field)...)
324 }
325
326 if fc, ok := fieldValue.(UpdateClausesInterface); ok {
327 field.Schema.UpdateClauses = append(field.Schema.UpdateClauses, fc.UpdateClauses(field)...)
328 }
329
330 if fc, ok := fieldValue.(DeleteClausesInterface); ok {
331 field.Schema.DeleteClauses = append(field.Schema.DeleteClauses, fc.DeleteClauses(field)...)
332 }
333 }
334 }
335
336 if field := schema.PrioritizedPrimaryField; field != nil {
337 switch field.GORMDataType {
338 case Int, Uint:
339 if _, ok := field.TagSettings["AUTOINCREMENT"]; !ok {
340 if !field.HasDefaultValue || field.DefaultValueInterface != nil {
341 schema.FieldsWithDefaultDBValue = append(schema.FieldsWithDefaultDBValue, field)
342 }
343
344 field.HasDefaultValue = true
345 field.AutoIncrement = true
346 }
347 }
348 }
349
350 // Cache the schema
351 if v, loaded := cacheStore.LoadOrStore(schemaCacheKey, schema); loaded {
352 s := v.(*Schema)
353 // Wait for the initialization of other goroutines to complete
354 <-s.initialized
355 return s, s.err
356 }
357
358 defer func() {
359 if schema.err != nil {
360 logger.Default.Error(context.Background(), schema.err.Error())
361 cacheStore.Delete(modelType)
362 }
363 }()
364
365 for _, cbName := range callbackTypes {
366 if methodValue := modelValue.MethodByName(string(cbName)); methodValue.IsValid() {
367 switch methodValue.Type().String() {
368 case "func(*gorm.DB) error":
369 expectedPkgPath := path.Dir(reflect.TypeOf(schema).Elem().PkgPath())
370 if inVarPkg := methodValue.Type().In(0).Elem().PkgPath(); inVarPkg == expectedPkgPath {
371 reflect.Indirect(reflect.ValueOf(schema)).FieldByName(string(cbName)).SetBool(true)
372 } else {
373 logger.Default.Warn(context.Background(), "In model %v, the hook function `%v(*gorm.DB) error` has an incorrect parameter type. The expected parameter type is `%v`, but the provided type is `%v`.", schema, cbName, expectedPkgPath, inVarPkg)
374 // PASS
375 }
376 default:
377 logger.Default.Warn(context.Background(), "Model %v don't match %vInterface, should be `%v(*gorm.DB) error`. Please see https://gorm.io/docs/hooks.html", schema, cbName, cbName)
378 }
379 }
380 }
381
382 // parse relationships
383 for _, field := range relationshipFields {
384 if schema.parseRelation(field); schema.err != nil {
385 return schema, schema.err
386 }
387 }
388
389 return schema, schema.err
390 }
391
392 func getOrParse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) {
393 modelType := reflect.ValueOf(dest).Type()
394
395 if modelType.Kind() != reflect.Struct {
396 for modelType.Kind() == reflect.Slice || modelType.Kind() == reflect.Array || modelType.Kind() == reflect.Ptr {
397 modelType = modelType.Elem()
398 }
399
400 if modelType.Kind() != reflect.Struct {
401 if modelType.PkgPath() == "" {
402 return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest)
403 }
404 return nil, fmt.Errorf("%w: %s.%s", ErrUnsupportedDataType, modelType.PkgPath(), modelType.Name())
405 }
406 }
407
408 if v, ok := cacheStore.Load(modelType); ok {
409 return v.(*Schema), nil
410 }
411
412 return Parse(dest, cacheStore, namer)
413 }