gorm源码2 tag映射

2019-12-23  本文已影响0人  不存在的里皮

参考

目的

分析model_struct.go下的ModelStruct, StructField 和Relationship

定义tag

首先, 你需要为实体类定义tag, 比如:

type User struct {
    Id       int64   `gorm:"primary_key;auto_increment"`
    Username string  `gorm:"type:varchar(20)"`
    Kind     string  `gorm:"type:varchar(20)"`
    Password string  `gorm:"type:varchar(32)"`
}

映射

User会被映射为下面的:

切入分析

这个文件为Scope定义了两个函数,GetModelStruct和GetStructFields。

概括函数作用

概括而言,该函数会

  1. 根据hashKey从modelStructsMap查找缓存,找到存放的ModelStruct。该key与scope.Value的类型有关。如果查到缓存就返回。
  2. 查不到缓存。根据scope.Value去寻找对应的结构体,解析tag并返回ModelStruct。
    • 该函数会对属性递归调用ModelStruct,进行解析
    • scope.Value是什么呢?就是db.Model(&user)或者db.Find(&user)里的那个user

函数步骤

  1. 根据scope.Value得到其对应的实体struct类型reflectType. 比如db.Model(&user)在此会得到User类型
  2. 查找缓存modelStructsMap
    • 若有则返回
    • 若无缓存,则分析该struct得到ModelStruct,并存入modelStructsMap
  3. 假如没缓存,则分析struct每个属性:
    • 通过parseTagSetting解析tag中"sql"或"gorm"开头的部分,并加载为map形式
    • 若tag中有-(gorm:"-",下同)字段,则field.IsIgnored = true,跳至4. 否则要分析这个属性
    • 处理PRIMARY_KEY字段
    • 若有DEFAULT字段,则有默认值,field.HasDefaultValue = true
    • 赋值indirectType,当fieldStruct.Type为指针时,indirectType则为最终指向的类型
      • indirectTypesql.Scanner*time.Time则做出对应处理
      • indirectType有EMBEDDED字段或为匿名struct,则调用for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields递归分析嵌套结构体,并遍历其属性(一般gorm.Model会遍历至此):
        • 处理子类的一些属性,比较重要的是"PRIMARY_KEY",会加入主键
      • 如果是slice或struct类型,也会进行对应的处理
    • 设置field.DBName:
    // Even it is ignored, also possible to decode db value into the field
    if value, ok := field.TagSettingsGet("COLUMN"); ok {
    field.DBName = value
    } else {
        field.DBName = ToColumnName(fieldStruct.Name)
    }
    
  4.  if len(modelStruct.PrimaryFields) == 0 {
         if field := getForeignField("id", modelStruct.StructFields); field != nil {
             field.IsPrimaryKey = true
             modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
         }
     }
    
    没有找到主键,则看是否有"id"属性,若有则设为主键
  5. modelStructsMap.Store(hashKey, &modelStruct)存入缓存

总结

核心是解析结构体的函数GetModelStruct,它会递归调用,并把tag中的信息解析到ModelStruct, StructField和Relationship中。

上一篇下一篇

猜你喜欢

热点阅读