美文网首页
gorm源码2 tag映射

gorm源码2 tag映射

作者: 不存在的里皮 | 来源:发表于2019-12-23 13:06 被阅读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会被映射为下面的:

    • ModelStruct 实体struct(比如User)会被映射至此,PrimaryFields []*StructFieldStructFields []*StructField会保存那些映射的属性
    • StructField 那些带tag的属性(比如Id, Username等)会被映射至此
    • Relationship 与其它数据库表相关的东西由该结构体管理(比如外检)



      箭头含义为“映射为”

    切入分析

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

    • var modelStructsMap sync.Map的作用是ModelStruct的缓存
    • GetStructFields会调用GetModelStruct,所以我们从GetModelStruct看起,该函数有450行左右,工作量很大。

    概括函数作用

    概括而言,该函数会

    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中。

    相关文章

      网友评论

          本文标题:gorm源码2 tag映射

          本文链接:https://www.haomeiwen.com/subject/pcianctx.html